Effectively an easy way to call setTimeout()
from within an async function.
note: This will only wait at least this many ms before execution continues.
const sleep = ms => new Promise(res => setTimeout(res, ms));
// Usage
await sleep(100);
// Method 1
async function myAsyncFunction () {
return new Promise(resolve => {
let condition = true;
function loop() {
while (condition) {
// Do work
}
if (requirement) {
resolve(data);
} else {
setTimeout(loop, 0); // continue next cycle
}
}
loop();
});
}
// Usage
const result = await myAsyncFunction();
Using await sleep
// Method #2
let condition = true;
let progress = 0;
async loop myAsyncFunction() {
const sleep = ms => new Promise(res => setTimeout(res, ms));
while (condition) {
await sleep(0); // continue next cycle
// Do work and update progress
progress = getProgress;
}
}
// Usage
await myAsyncFunction();