1.Promise.all 并行執(zhí)行promise
getA和getB并行執(zhí)行,然后輸出結(jié)果。如果有一個錯誤,就拋出錯誤
/**
* 每一個promise都必須返回resolve結(jié)果才正確
* 每一個promise都不處理錯誤
*/
const getA = new Promise((resolve, reject) => {
//模擬異步任務(wù)
setTimeout(function(){
resolve(2);
}, 1000)
})
.then(result => result)
const getB = new Promise((resolve, reject) => {
setTimeout(function(){
// resolve(3);
reject('Error in getB');
}, 1000)
})
.then(result => result)
Promise.all([getA, getB]).then(data=>{
console.log(data)
})
.catch(e => console.log(e));
getA和getB并行執(zhí)行,然后輸出結(jié)果。總是返回resolve結(jié)果
/**
* 每一個promise自己處理錯誤
*/
const getA = new Promise((resolve, reject) => {
//模擬異步任務(wù)
setTimeout(function(){
resolve(2);
}, 1000)
})
.then(result => result)
.catch(e=>{
})
const getB = new Promise((resolve, reject) => {
setTimeout(function(){
// resolve(3);
reject('Error in getB');
}, 1000)
})
.then(result => result)
.catch(e=>e)
Promise.all([getA, getB]).then(data=>{
console.log(data)
})
.catch(e => console.log(e));
2.順序執(zhí)行promise
先getA然后getB執(zhí)行,最后addAB
- 2.1 方法一——連續(xù)使用then鏈?zhǔn)讲僮?/li>
function getA(){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(2);
}, 1000);
});
}
function getB(){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(3);
}, 1000);
});
}
function addAB(a,b){
return a+b
}
function getResult(){
var obj={};
Promise.resolve().then(function(){
return getA()
})
.then(function(a){
obj.a=a;
})
.then(function(){
return getB()
})
.then(function(b){
obj.b=b;
return obj;
})
.then(function(obj){
return addAB(obj['a'],obj['b'])
})
.then(data=>{
console.log(data)
})
.catch(e => console.log(e));
}
getResult();
- 2.2 方法二——使用promise構(gòu)建隊列
function getResult(){
var res=[];
// 構(gòu)建隊列
function queue(arr) {
var sequence = Promise.resolve();
arr.forEach(function (item) {
sequence = sequence.then(item).then(data=>{
res.push(data);
return res
})
})
return sequence
}
// 執(zhí)行隊列
queue([getA,getB]).then(data=>{
return addAB(data[0],data[1])
})
.then(data => {
console.log(data)
})
.catch(e => console.log(e));
}
getResult();
- 2.3方法三——使用async、await實現(xiàn)類似同步編程
function getResult(){
async function queue(arr) {
let res = []
for (let fn of arr) {
var data= await fn();
res.push(data);
}
return await res
}
queue([getA,getB])
.then(data => {
return addAB(data[0],data[1])
}).then(data=>console.log(data))
}
3. 總結(jié)
實現(xiàn)異步隊列函數(shù)的三種方式
方法一——連續(xù)使用then鏈?zhǔn)讲僮?br> 方法二——使用promise構(gòu)建隊列
方法三——使用async、await實現(xiàn)類似同步編程,async函數(shù)內(nèi)部實現(xiàn)同步
參考
Promise的順序執(zhí)行和并行執(zhí)行
構(gòu)建Promise隊列實現(xiàn)異步函數(shù)順序執(zhí)行
補(bǔ)充
ES6 Promise中斷
中斷或取消Promise鏈的可行方案
(1)reject()
(2)throw new Error()
一般來說,不要在then方法里面定義 reject 狀態(tài)的回調(diào)函數(shù)(即then的第二個參數(shù)),總是使用catch方法。