Last active
March 13, 2023 12:22
-
-
Save rauschma/8b97254d19e039bfb8003b6ef583fbfd to your computer and use it in GitHub Desktop.
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
// 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
awesome