Skip to content

Instantly share code, notes, and snippets.

@samlaf
Created March 18, 2022 05:34
Show Gist options
  • Save samlaf/d1666efb34c57e8af3b74b2e004875b7 to your computer and use it in GitHub Desktop.
Save samlaf/d1666efb34c57e8af3b74b2e004875b7 to your computer and use it in GitHub Desktop.
js callback vs promise vs async/await
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