Skip to content

Instantly share code, notes, and snippets.

@biobii
Created May 26, 2018 02:11
Show Gist options
  • Save biobii/14e5f46cf33682265594e96b1c44d06c to your computer and use it in GitHub Desktop.
Save biobii/14e5f46cf33682265594e96b1c44d06c to your computer and use it in GitHub Desktop.
Understanding the difference between callback, promise and async await in JavaScript.
/*-----------------------
* CALLBACK
*-----------------------
*/
function get (callback) {
return setTimeout(() => callback('learn'), 100);
}
function process (value, callback) {
return setTimeout(() => callback(`${value} asynchronous`), 100);
}
function main () {
get(value => {
process (value, res => console.log(res));
});
}
main();
/* ---- END OF CALLBACK ---- */
/*-----------------------
* PROMISE
*-----------------------
*/
function get (callback) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('learn'), 100);
});
}
function process (value, callback) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(`${value} asynchronous`), 100);
});
}
function main () {
get()
.then(process)
.then(result => console.log(result));
}
main();
/* ---- END OF PROMISE ---- */
/*-----------------------
* ASYNC AWAIT
*-----------------------
*/
async function get (callback) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('learn'), 100);
});
}
async function process (value, callback) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(`${value} asynchronous`), 100);
});
}
async function main () {
let val = await get();
let result = await process(val);
console.log(result);
}
main();
/* ---- END OF ASYNC AWAIT ---- */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment