I want to iterate an array in Javascript and one element will take some time to get processed.
I want to till that element is processed, wait for that.
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)
});
Expected Output - Hello World How ARE You Today.
Actual - Hello World How You Today
setTimeout. Remove that and its synchronous again. What are you really asking? This hints heavily at an XY Problem - are you asking how to wait in the loop for an async action to complete?forEachloop synchronous. It ignores the return value and calls the next function after the current function returned.forEachis still synchronous though?forEachis synchronous. But not the functions inside. And you can't makeforEachwait for an async function.