Last active
January 14, 2021 15:25
-
-
Save thiagosouza/7fdde1cf2a2e3bc14ad21940e367fcf5 to your computer and use it in GitHub Desktop.
[Javascript / sync vs async promises] Synchronous vs Asynchronous Promises in Javascript #javascript
This file contains hidden or 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
//asynchronous | |
; (async () => { | |
console.time('testAsynchronous') | |
let start = new Date() | |
let hrstart = process.hrtime() | |
let testAsync = await Promise.all([ | |
Promise.resolve(1), | |
new Promise(async (resolve, reject) => { | |
console.log("starting 2") | |
return setTimeout(resolve, 1000, 2); | |
}), | |
new Promise(async (resolve, reject) => { | |
console.log("starting 3") | |
return setTimeout(resolve, 3000, 3); | |
}), | |
new Promise(async (resolve, reject) => { | |
console.log("starting 4") | |
return setTimeout(resolve, 4000, 4); | |
}), | |
]); | |
console.log(testAsync); | |
let end = new Date() - start, | |
hrend = process.hrtime(hrstart) | |
console.info('Execution time: %dms', end) | |
console.info('Execution time (hr): %ds %dms', hrend[0], hrend[1] / 1000000) | |
console.timeEnd('testAsynchronous') | |
})(); | |
//synchronous | |
(async () => { | |
console.time('testSynchronous') | |
let start = new Date() | |
let hrstart = process.hrtime() | |
let testSync = await Promise.all([ | |
Promise.resolve(1), | |
await new Promise(async (resolve, reject) => { | |
console.log("starting 2") | |
return setTimeout(resolve, 1000, 2); | |
}), | |
await new Promise(async (resolve, reject) => { | |
console.log("starting 3") | |
return setTimeout(resolve, 3000, 3); | |
}), | |
await new Promise(async (resolve, reject) => { | |
console.log("starting 4") | |
return setTimeout(resolve, 4000, 4); | |
}), | |
]); | |
console.log(testSync); | |
let end = new Date() - start, | |
hrend = process.hrtime(hrstart) | |
console.info('Execution time: %dms', end) | |
console.info('Execution time (hr): %ds %dms', hrend[0], hrend[1] / 1000000) | |
console.timeEnd('testSynchronous') | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment