Forked from rauschma/callbacks-promises-asyncfuncs.js
Created
February 17, 2019 14:21
-
-
Save bhaveshgohel/31d59aa9aaf6a95c0c064fd1882b2595 to your computer and use it in GitHub Desktop.
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
// From callbacks to Promises to async functions | |
function callbackFunc(x, callback) { | |
f1(x, (err1, result1) => { | |
if (err1) { | |
console.error(err1); | |
callback(err1); | |
return; | |
} | |
f2(result1, (err2, result2) => { | |
if (err2) { | |
console.error(err2); | |
callback(err2); | |
return; | |
} | |
console.log(result2); | |
callback(null, result2); | |
}); | |
}); | |
} | |
function promiseFunc(x) { | |
return f1(x) | |
.then(result1 => { | |
return f2(result1); | |
}) | |
.then(result2 => { | |
console.log(result2); | |
return result2; | |
}) | |
.catch(err => { | |
console.error(err); | |
throw err; | |
}); | |
} | |
async function asyncFunc(x) { | |
try { | |
const result1 = await f1(x); | |
const result2 = await f2(result1); | |
console.log(result2); | |
return result2; | |
} catch (err) { | |
console.error(err); | |
throw err; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment