如何在JavaScript中创建for循环同步



我想在Javascript中迭代一个数组,其中一个元素需要一些时间来处理。

我想要直到那个元素被处理,等待那个

var splittedText = ["Hello", "World", "How", "Are", "You", "Today"];
var text = "";
splittedText.forEach((name) => {
if (name === "Are") {
setTimeout(() => {
text = text + "ARE"
}, 2000)
} else {
text = text + name + " ";
}
console.log(text)
});

预期输出-你好世界你今天好吗

实际- Hello World How You Today

不能让forEach循环等待异步函数。它忽略返回值,并在当前函数返回后调用下一个函数。您可以使用for ... of ...循环并等待承诺。但await只能在async函数(或asyncIIFE)中使用。

(async function() {
const splittedText = ["Hello", "World", "How", "Are", "You", "Today"];
let text ="";
for (const name of splittedText) {
if (name === "Are") {
await new Promise((resolve) => {
setTimeout(() => {
text = text + "ARE";
resolve();
}, 2000);
});
} else {
text += name + " ";
}  
console.log(text)
};
})();

const firstOperation = (word) => word
const secondOperation = (word) => new Promise(
(resolve) => setTimeout(
() => resolve(word), 
1000
)
)
const operations = [firstOperation('Hello'), firstOperation('World'), firstOperation('How'), secondOperation('Are'), firstOperation('you'), firstOperation('today')]
Promise.all(operations).then(word => console.log(word))

最新更新