Created
September 18, 2019 09:54
-
-
Save guillaumegarcia13/d4e7b292548e88c9de192a4b6da247ea to your computer and use it in GitHub Desktop.
sleep (await version)
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
var sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); | |
// Usage | |
// within an 'async' function | |
await sleep(2000); | |
// And without async? | |
// scenarios like the following do not work unfortunately | |
console.log('Wait for 5s...'); | |
(async function() { | |
await sleep(5000); | |
})(); | |
console.log('OK! Waited 5s'); | |
// indeed, you should have an async which is precisely what you want to avoid | |
console.log('Wait for 5s...'); | |
await (async function() { | |
await sleep(5000); | |
})(); | |
console.log('OK! Waited 5s'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment