Categories
JavaScript Answers

How to use while loop with promises with JavaScript?

Spread the love

To use while loop with promises with JavaScript, we use async and await.

For instance, we write

const loop = async (value) => {
  let result = null;
  while (result !== "ok") {
    console.log(value);
    result = await doSomething(value);
  }
};

to define the loop function.

In it, we use a while loop that runs until result isn’t 'ok'.

In the loop, we call doSomething which returns a promise and we use await to wait for the promise to finish and return the resolved value.

We set the resolved value to result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *