ChenPt / dailyNote

dailyNode for myself
https://github.com/ChenPt/dailyNote/issues
0 stars 0 forks source link

2020/03/31 Promise 顺序执行 #39

Open ChenPt opened 4 years ago

ChenPt commented 4 years ago
function getResult(result, val) {
  val && result.push(val)
  return result
}

const pushResult = getResult.bind(null, [])

const chainResult = getResult.bind(null, [])

const orderResult = getResult.bind(null, [])

function task(idx, type) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const num = idx + 1
      resolve(num)
      // console.log(`${type}:  ${num}`)
    }, Math.random() * 2000)
  })
}

function generatorFn(num, type) {
  // 返回一个包含了5个task的数组,每个task都会返回一个Promise对象
  return Array.from(new Array(num)).map((item, idx) => task.bind(null, idx, type))
}

// Promise.all来执行task list
Promise.all(generatorFn(5, 'all').map(fn => fn().then(pushResult))).then(result => console.log('all: ', pushResult())) // 随机

const taskFn = generatorFn(5, 'all')
// 按顺序执行task
Promise.resolve()
.then(taskFn[0])
.then(chainResult)
.then(taskFn[1])
.then(chainResult)
.then(taskFn[2])
.then(chainResult)
.then(taskFn[4])
.then(chainResult)
.then(result => console.log('chain: ', chainResult())) // [1,2,3,5]

// 利用reduce来按顺序执行task list
const order = generatorFn(5, 'order').reduce((promise, cur) => {
  return promise.then(cur).then(orderResult)
}, Promise.resolve())
order.then(res => console.log('order: ', orderResult())) // order: [1, 2, 3, 4, 5]

Promise顺序执行可以手动编写then,也可以利用for循环去调用then执行,for循环可转变为reduce实现