Created
March 17, 2020 16:03
-
-
Save harshamv/71ffe07793fdfca621dbf4bec3e01ca7 to your computer and use it in GitHub Desktop.
Async and Await Function
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
let counter = 0; | |
function doSomethingAsync(id, start) { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
counter++; | |
const stop = new Date(); | |
const runningTime = getSeconds(start, stop); | |
resolve(`result${id} completed in ${runningTime} seconds`); | |
}, 2000); | |
}); | |
} | |
function getSeconds(start, stop) { | |
return (stop - start) / 1000; | |
} | |
async function test() { | |
console.log('Awaiting 3 Async calls'); | |
console.log(`Counter before execution: ${counter}`); | |
const start = new Date(); | |
const [result1, result2, result3] = await Promise.all([ | |
doSomethingAsync(1, new Date()), | |
doSomethingAsync(2, new Date()), | |
doSomethingAsync(3, new Date()) | |
]); | |
const stop = new Date(); | |
console.log(result1, result2, result3); | |
console.log(`Counter after all ran: ${counter}`); | |
console.log(`Total time to run: ${getSeconds(start, stop)}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment