Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active March 13, 2023 12:22
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rauschma/8b97254d19e039bfb8003b6ef583fbfd to your computer and use it in GitHub Desktop.
Save rauschma/8b97254d19e039bfb8003b6ef583fbfd to your computer and use it in GitHub Desktop.
// 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;
}
}
@Dushusir
Copy link

perfect

@dandgerson
Copy link

awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment