温故知新(九五)promise 并发 和 按顺序执行

并发可以直接使用 Promise.all 进行多个 Promise 并发执行

按顺序执行:

        1.可以使用 async 函数里面的 for of 进行迭代

        2.可以使用 reduce 函数进行迭代调用

调用的promise

const sleep = () => {
  return new Promise((resolve, reject) => {
    setTimeout(function(){
      console.log('sleep')
      resolve()
    }, 1000)
  })
}


const promiseList = [
  sleep,
  sleep,
  sleep
]

并发执行:

console.log('Promise.all start', new Date().getTime())
Promise.all(
  promiseList.map(item => item())
).then(() => {
  console.log('Promise.all end', new Date().getTime())
})

并发执行还可以使用 async await 函数,更加简洁明了

async function fn() {
  const sleep1 = sleep1()
  const sleep2 = sleep2()
  const sleep3 = sleep3()
  // 下面三个写的顺序跟总共所花的时间无关,无论谁先谁后,总共时长一样
  const res1 = await sleep1
  const res2 = await sleep2
  const res3 = await sleep3
  console.log(res1, res2, res3)
  // 上面总体等同于:
  /**
  const sleep1 = new Promise((resolve) => {
    sleep1().then(resolve)
  })
  const sleep2 = new Promise((resolve) => {
    sleep2().then(resolve)
  })
  
  sleep1.then(()=>{
    sleep2.then(()=>{
      
    })
  })
  
  **/
}

 

按顺序迭代:

1、async  for of

async function forOfPromise() {
  console.log('for of start', new Date().getTime())
  async function forOfLoop() {
    for (const promiseInstance of promiseList) {
      await promiseInstance()
    }
  }
  await forOfLoop()
  console.log('for of end',  Date.now())
}
forOfPromise()

 2、reduce

const promiseChain = promiseList.reduce((prev, current) => {
  // 如果是实例
  if (prev.then) {
    return prev.then(current)
  }
  // 如果是构造函数
  return prev().then(current)
})
promiseChain.then(_=>console.log('promisechain completed'))

上面的 reduce 可以给一个初始值

const promiseChain2 = promiseList.reduce((prev, cur) => {
  return prev.then(cur)
}, Promise.resolve())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值