<分区>
我在 Promise.then
方法中使用了 delay
函数生成器
function delay(msec) {
return (value) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(value);
}, msec);
});
}
}
当我在没有循环的情况下使用 delay
函数时,它工作正常:
var promise = Promise.resolve();
promise
.then(() => console.log(1))
.then(delay(1000))
.then(() => console.log(2))
.then(delay(1000))
.then(() => console.log(3))
.then(delay(1000));
但是当我在循环中使用它时,所有数字都会被毫无延迟地打印出来:
var loopPromise = Promise.resolve();
for (let i = 1; i <= 3; i++) {
loopPromise
.then(() => console.log(i))
.then(delay(1000));
}
为什么 promise 在循环中的工作方式不同?我该如何解决这个循环行为?