Simplest JS promise tutorial using await / async

Rabu, 24 April 2024, 4:30 pm
I often forgot how to use output of a function that uses Promise. Which callback to use? .then()
/ .catch()
/ .finally()
/ .all()
?
So here’s the easiest way to use it & remember.
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
async function get_name(value) { | |
return new Promise((resolve, reject) => { // must return Promise instance from async function | |
setTimeout(() => { // emulate asynchronous, long running task | |
if (value) { | |
resolve(value); // success | |
} else { | |
reject(false); // fail | |
} | |
}, 3000); | |
}); | |
} | |
// await can only be used inside an async function | |
async function main() { | |
try { | |
var name = await get_name(); | |
console.log('name=', name); | |
} catch (e) { // to get rejected output, need to try-catch | |
console.log('e=', e); | |
} | |
try { | |
var name2 = await get_name('john'); | |
console.log('name2=', name2); | |
} catch (e2) { | |
console.log('e2=', e2); | |
} | |
} | |
main(); | |
// output after 3 secs: | |
// e=false | |
// output after 6 secs: | |
// name2=john |
Photos from:
- https://www.freecodecamp.org/news/javascript-promise-tutorial-how-to-resolve-or-reject-promises-in-js/
- https://medium.com/from-code-to-beyond/stop-using-promise-all-in-javascript-a8157bc692bd
26 April 2024
Connection timed out when running commands in macOS
23 April 2024