Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nafeu/9649dc9cae538aa686792052435b6cc0 to your computer and use it in GitHub Desktop.
Save nafeu/9649dc9cae538aa686792052435b6cc0 to your computer and use it in GitHub Desktop.
// promisified 'setTimeout' function
function delay(delayedFunction, time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
resolve(delayedFunction());
} catch (error) {
reject(error.message);
}
}, time);
});
}
// top-level async declaration
async function main() {
// await using a for...of loop
const delaysInMs = [3000, 2000, 1000];
for (const time of delaysInMs) {
console.log(await delay(() => `print after ${time / 1000} second(s)`, time));
}
// await using a while loop
let count = 0;
const max = 100;
while (count < max) {
const result = await delay(() => `${++count} of ${max} lines...`, 1000);
console.log(result);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment