Simplest JS promise tutorial using await / async

9B5E99A5-1142-492D-A96B-D3B366B21C03.jpeg

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.

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:

Komentar (0):

FB: https://www.facebook.com/100810608155424/posts/1104943984005846/

Tulis komen: