面试题-Promise顺序执行

7,684 阅读1分钟

题目描述

有一个数组,数组元素是返回Promise对象的函数,怎样顺序执行数组中的函数,即在前一个数组中的Promise resolve之后才执行下一个函数?

准备数据

function generatePromiseFunc(index) {
    return function () {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(index)
                resolve(index)
            }, 1000)
        })
    }
}

const list = []

for(let i = 0; i < 10; i++) {
    list.push(generatePromiseFunc(i))
}

解法1

// 递归调用
function promise_queue(list, index) {
    if (index >= 0 && index < list.length) {
        list[index]().then(() => {
            promise_queue(list, index + 1)
        })
    }
}
promise_queue(list, 0)

解法2

// 使用 await & async
async function promise_queue(list) {
    let index = 0
    while (index >= 0 && index < list.length) {
        await list[index]()
        index++
    }
}
promise_queue(list)

解法3

// 使用Promise.resolve()
function promise_queue(list) {
  var sequence = Promise.resolve()
  list.forEach((item) => {
    sequence = sequence.then(item)
  })
  return sequence
}
// 这个需要解释下,遍历数组,每次都把数组包在一个Promise.then()中,相当于list[0]().then(list[1]().then(list[2]().then(...))),
// 这样内层Promise依赖外层Promise的状态改变,从而实现逐个顺序执行的效果

请问大家还有没有其他的解法呢?