-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

8
  • 5
    You've specifically made it Asynchronous by introducing a 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? Commented Feb 15, 2021 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. Commented Feb 15, 2021 at 11:11
  • @ThomasSablik a forEach is still synchronous though? Commented Feb 15, 2021 at 11:13
  • @evolutionxbox Yes, forEach is synchronous. But not the functions inside. And you can't make forEach wait for an async function. Commented Feb 15, 2021 at 11:14
  • 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 Commented Feb 15, 2021 at 11:21

2 Answers 2

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)
    };
})();

Sign up to request clarification or add additional context in comments.

Comments

-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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.