【ES6】Promise的串行和并行

一、并行运行:

Promise提供了Promise.all,Promise.race,Promise.allSettled等多个Promise对象间的运行关系,如果并行运行可以用Promise.all来进行处理:

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

二、串行运行:

2.1、promises串行运行(问题:遇到reject时中断运行

const serialPromises = function (promises) {
  promises.reduce((prev, next) => prev.then(next), Promise.resolve());
}

测试代码(均resolve):

const fn1 = function (args) {
  console.log('fn1',args)
  return Promise.resolve('111')
}
const fn2 = function (args) {
  console.log('fn2',args)
  return Promise.resolve('222')
}
const fn3 = function (args) {
  console.log('fn3',args)
  return Promise.resolve('333')
}
serialPromises([fn1, fn2, fn3])

结果:

 

上面serialPromises有个问题如果有个fn2执行reject那么执行链会发生中断

测试代码(包含reject):

const fn1 = function (args) {
  console.log('fn1',args)
  return Promise.resolve('111')
}
const fn2 = function (args) {
  console.log('fn2',args)
  return Promise.reject('222')
}
const fn3 = function (args) {
  console.log('fn3',args)
  return Promise.resolve('333')
}
serialPromises([fn1, fn2, fn3])

结果:

 

 2.2、promise串行运行,遇到reject也不会中断(问题:但是reject的方法会调用两次):

const serialPromises2 = function (promises) {
  promises.reduce((prev, next) => prev.then(next).catch(next), Promise.resolve());
}

测试代码(2.1中包含reject的测试代码):

serialPromises2([fn1, fn2, fn3])

测试结果:

 

这个方法也有个问题是如果有fn2执行reject,那么那个fn2会执行两次,这是因为p.catch等价于p.then(undefined, onRejected)

2.3、promise串行运行(2.2问题解决)

const serialPromises3=function(promises){
  const process=function(i,args){
    const curr=promises[i]
    const next=function(res){process(i+1,res)}
    if(curr)curr(args).then(next).catch(next)
  }
  process(0)
}

测试代码(2.1中包含reject的测试代码):

serialPromises3([fn1, fn2, fn3])

测试结果

转自:https://www.cnblogs.com/zhuxianguo/p/11445952.html

也可以参照:https://blog.csdn.net/liushan633/article/details/84303500

 

posted @ 2020-12-17 20:38  vickylinj  阅读(1566)  评论(0编辑  收藏  举报