Created
May 26, 2018 02:11
-
-
Save biobii/14e5f46cf33682265594e96b1c44d06c to your computer and use it in GitHub Desktop.
Understanding the difference between callback, promise and async await in JavaScript.
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
/*----------------------- | |
* 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