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
.