Created
March 18, 2022 05:34
-
-
Save samlaf/d1666efb34c57e8af3b74b2e004875b7 to your computer and use it in GitHub Desktop.
js callback vs promise vs async/await
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
function performLongTask(cb: (err:any, res: any) => any) { | |
const returnValue = 42; | |
setTimeout(() => cb(null, returnValue), 3000) | |
} | |
performLongTask((err, res) => { | |
if (err) throw new Error('we got an error'); | |
console.log("callback:", res) | |
}) | |
function performLongTaskPromise() { | |
return new Promise(function(resolve, reject) { | |
performLongTask((err, res) => { | |
if (err) reject(err) | |
resolve(res) | |
}) | |
}) | |
} | |
performLongTaskPromise().then(res => {console.log("Promise.then:", res)}, err => {throw new Error('we got an error')}); | |
(async () => { | |
let res; | |
try { | |
res = await performLongTaskPromise() | |
} catch (err) { | |
throw new Error('we got an error'); | |
} | |
console.log("async/await:", res) | |
})() | |
// this prints all 3 results, after 3s: | |
// "callback:", 42 | |
// "Promise.then:", 42 | |
// "async/await:", 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: read and understand https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/