这段代码等待 2s,然后 console.log 的每个元素直接。我如何更改此 forEach 以等待每次超时完成,然后再循环到下一个超时?所以我想要的是经过 2 秒,然后记录“1”,然后经过另一个 2 秒,然后记录“2”等。我查看了 promise (此处实现了一半),但我不明白它是如何工作的.
MyArray = [1, 2, 3];
MyArray.forEach(async element => {
await setTimeout(() => {
console.log(element);
}, 2000);
});
最佳答案
异步不适用于 setTimeout
,您可以返回一个稍后解析的 promise ,并在解析时返回下一个值等。 Reduce 可以为您做到这一点:
const MyArray = [1, 2, 3];
const later = (howLong, element) =>
new Promise(
resolve =>
setTimeout(() => {
console.log(element);
resolve(element)
}, howLong)
);
MyArray.reduce(
(all, element) =>
all.then(
() => later(2000, element)
),
Promise.resolve()
).then(()=>console.log("done"));
下面是并列的:
const MyArray = [1, 2, 3];
Promise.all(
MyArray.map(element =>
new Promise(
resolve=>
setTimeout(() => {
console.log(element);
resolve(element)
}, 2000)
)
)
).then(
results=>console.log("results",results)
)
关于javascript - 让 ForEach 在每个循环之前完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49979527/