-1

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

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
AMOD MAHAJAN
  • 152
  • 1
  • 10
  • 5
    You've specifically made it **A**synchronous by introducing a `setTimeout`. Remove that and its synchronous again. What are you _really_ asking? This hints heavily at an [XY Problem](http://xyproblem.info) - are you asking how to wait in the loop for an async action to complete? – Jamiec Feb 15 '21 at 11:10
  • You can't make a `forEach` loop synchronous. It ignores the return value and calls the next function after the current function returned. – Thomas Sablik Feb 15 '21 at 11:11
  • @ThomasSablik a `forEach` is still synchronous though? – evolutionxbox Feb 15 '21 at 11:13
  • @evolutionxbox Yes, `forEach` is synchronous. But not the functions inside. And you can't make `forEach` wait for an async function. – Thomas Sablik Feb 15 '21 at 11:14
  • @jamiec Yes, I purposely used setTimeout. I want to know how to wait in the loop for an async action to complete – AMOD MAHAJAN Feb 15 '21 at 11:19
  • @ThomasSablik Pls suggest another approach. – AMOD MAHAJAN Feb 15 '21 at 11:20
  • Don't use a `forEach` loop. Use a `for ... of ...` loop instead. – Thomas Sablik Feb 15 '21 at 11:20
  • 1
    So your title is misleading then - you're not asking how to make a loop synchronous (they already are!!), you're asking how to wait for an asynchronous action in a loop. For which there are about a million duplicates – Jamiec Feb 15 '21 at 11:21

2 Answers2

0

You can't make a forEach loop wait for an asynchronous function. It ignores the return value and calls the next function after the current function returned. You can use a for ... of ... loop and await the promise. But await can only be used inside an async function (or inside an async IIFE).

(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)
    };
})();
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
-2
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))
Jason Van Malder
  • 587
  • 1
  • 5
  • 15