ES6 Promise 並行執行和順序執行

2021-10-09 11:16:13 字數 1834 閱讀 7310

1.promise.all 並行執行promise

geta和getb並行執行,然後輸出結果。如果有乙個錯誤,就丟擲錯誤

/**

* 每乙個promise都必須返回resolve結果才正確

* 每乙個promise都不處理錯誤

*/const geta = new promise((resolve, reject) => , 1000)

}).then(result => result)

const getb = new promise((resolve, reject) => , 1000)

}).then(result => result)

promise.all([geta, getb]).then(data=>)

.catch(e => console.log(e));

geta和getb並行執行,然後輸出結果。總是返回resolve結果

/**

* 每乙個promise自己處理錯誤

*/const geta = new promise((resolve, reject) => , 1000)

}).then(result => result)

.catch(e=>)

const getb = new promise((resolve, reject) => , 1000)

}).then(result => result)

.catch(e=>e)

promise.all([geta, getb]).then(data=>)

.catch(e => console.log(e));

2.順序執行promise

先geta然後getb執行,最後addab

function geta(), 1000);

});}

function getb(), 1000);

});}

function addab(a,b)

function getresult();

promise.resolve().then(function())

.then(function(a))

.then(function())

.then(function(b))

.then(function(obj))

.then(data=>)

.catch(e => console.log(e));

}getresult();

function getresult())

})return sequence

}// 執行佇列

queue([geta,getb]).then(data=>)

.then(data => )

.catch(e => console.log(e));

}getresult();

function getresult()

return await res

}queue([geta,getb])

.then(data => ).then(data=>console.log(data))

}

3. 總結

實現非同步佇列函式的三種方式

方法一——連續使用then鏈式操作

方法二——使用promise構建佇列

方法三——使用async、await實現類似同步程式設計,async函式內部實現同步

ES6 Promise 並行執行和順序執行

geta和getb並行執行,然後輸出結果。如果有乙個錯誤,就丟擲錯誤 每乙個promise都必須返回resolve結果才正確 每乙個promise都不處理錯誤 const geta newpromise resolve,reject 1000 then result result const get...

ES6 Promise基本用法

1 promise是什麼 promise是非同步程式設計的一種解決方案,在es6中promise被列為了正式規範,統一了用法,原生提供了promise物件。2 基礎用法 resolve代表成功 reject失敗 都是乙個函式 let p new promise function reslove,re...

ES6 Promise使用介紹

1 什麼是promise promise 是非同步程式設計的一種解決方案,比傳統的解決方案 函式和事件 更合理和更強大。這麼說可能不夠直觀的理解,看下面的兩個例子 callback 函式 function getcallback n,callback 2000 getcallback 3,funct...