最佳答案
for (let i = 0; i < 10; i++) {
const promise = new Promise((resolve, reject) => {
const timeout = Math.random() * 1000;
setTimeout(() => {
console.log(i);
}, timeout);
});
// TODO: Chain this promise to the previous one (maybe without having it running?)
}
以上将产生以下随机输出:
6
9
4
8
5
1
7
2
3
0
任务很简单: 确保每个承诺只在另一个(.then()
)之后运行。
不知道为什么,我找不到办法。
我尝试了生成器函数(yield
) ,尝试了返回承诺的简单函数,但最终总是归结为同一个问题: 循环是同步的。
对于 异步,我只需使用 async.series()
。
你怎么解决这个问题?