有一个数组,数组元素是返回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))
}
复制代码
// 递归调用
function promise_queue(list, index) {
if (index >= 0 && index < list.length) {
list[index]().then(() => {
promise_queue(list, index + 1)
})
}
}
promise_queue(list, 0)
复制代码
// 使用 await & async
async function promise_queue(list) {
let index = 0
while (index >= 0 && index < list.length) {
await list[index]()
index++
}
}
promise_queue(list)
复制代码
// 使用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的状态改变,从而实现逐个顺序执行的效果
复制代码
请问你们还有没有其余的解法呢?promise