Skip to content
大纲

promise 实战应用

限制异步操作的并发个数,并尽快完成

promise 解决实际问题

  • 将异步操作任务队列,转换成确定的顺序执行
js
// 两种方式的区别?
// 这里的p.then里面是异步微任务,又将将状态的转变放入了宏任务当中
const arr = [1, 2, 3]
arr.reduce(
  (p, x) =>
    p.then(() => new Promise((r) => setTimeout(() => r(console.log(x)), 1000))),
  Promise.resolve()
)

// p.then()里面的参数如果不是函数的话,会发生透传,那.then()里的代码是会执行的
// 所以这里的p.then 相当于执行了一段同步代码,将状态的转变放入了宏任务当中
const result = arr.reduce(
  (p, x) =>
    p.then(new Promise((r) => setTimeout(() => r(console.log(x)), 1000))),
  Promise.resolve()
)

实现红绿灯循环亮功能

TODO