ES6 Promise 并行执行和顺序执行

作者: 卓三阳 | 来源:发表于2018-10-02 23:09 被阅读10次
1.Promise.all 并行执行promise

getA和getB并行执行,然后addAB

const getA = new Promise((resolve, reject) => {
   setTimeout(function(){
     var a=1;
     resolve(a);
   }, 1000) 
})

const getB = new Promise((resolve, reject) => {
   setTimeout(function(){
     var b=2;
     resolve(b);
   }, 1000) 
})

function addAB(a,b){
    return new Promise((resolve,reject)=>{
        resolve(a+b);
    })
}

Promise.all([getA, getB])
.then(data=>{
    return addAB(data[0],data[1]);
})
.then(data=>{
    console.log(data)
 })
.catch(e => console.log(e));

2.顺序执行promise

先getA然后getB执行,最后addAB

  • 2.1使用then链式操作
function getA(){
      return  new Promise(function(resolve, reject){ 
      setTimeout(function(){     
            var a=1;
            resolve(a);
        }, 1000);
    });
}
 
function getB(){
    return  new Promise(function(resolve, reject){       
        setTimeout(function(){
            var b=2
            resolve(b);
        }, 1000);
    });
}
 
function addAB(a,b){
     return new Promise(function(resolve, reject){     
        setTimeout(function(){
            var data=a+b;
            resolve(data);
        }, 1000);
    });
}


function getResult(){
    var  obj={};
    Promise.resolve().then(function(){
        return  getA() 
    })
    .then(function(a){
         obj.a=a;
         return obj;
    })
    .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)
    });

}

getResult();
  • 2.2构建队列
function getResult(){
    var res=[];
    // 构建队列
    function queue(arr) {
      var sequence = Promise.resolve();
      arr.forEach(function (item) {
        sequence = sequence.then(item).then(data=>{
            res.push(data);
            return res
        })
      })
      return sequence
    }

    // 执行队列
    queue([getA,getB]).then(data=>{
        return addAB(data[0],data[1])
    })
    .then(data => {
        console.log(data)
    })

}
  • 2.3方法三(使用async、await构建队列)
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))


}

参考

http://zyy1217.com/2017/03/25/promise/
https://blog.csdn.net/u011500781/article/details/73883903
https://blog.csdn.net/qq_34178990/article/details/81122162


补充

注意:async保证async函数内部实现同步

function timeout(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function asyncPrint(value, ms) {
  await timeout(ms);
  console.log(value);
}

asyncPrint('hello world', 50);
console.log('this is direct');
//this is direct
//hello world

ES6 Promise中断
中断或取消Promise链的可行方案

(1)reject()
(2)throw new Error()
一般来说,不要在then方法里面定义 Reject 状态的回调函数(即then的第二个参数),总是使用catch方法。

相关文章

网友评论

    本文标题:ES6 Promise 并行执行和顺序执行

    本文链接:https://www.haomeiwen.com/subject/vkmgoftx.html