Created
January 15, 2021 01:50
-
-
Save nafeu/9649dc9cae538aa686792052435b6cc0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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