Write asynchronous code that reads like normal code. await pauses only its own function; errors arrive in catch.
JavaScript · beginner · 8 min · 22 steps · free
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: 'Ada' });
else reject(new Error('no such user'));
}, 200);
});
}
async function showUser(id) {
try {
const user = await fetchUser(id);
console.log('found', user.name);
} catch (err) {
console.log('failed:', err.message);
}
}
showUser(1);
showUser(-1);
console.log('requests sent');fetchUser, showUser already exist. This is called hoisting.fetchUser(), with id = 1. It gets its own variables.(resolve, reject) => { setTim…, with resolve = a built-in function and reject = a built-in function. It gets its own variables.setTimeout hands the callback to a timer and returns at once. It will run after 200 ms, once the call stack is empty: see Timers waiting.fetchUser returns Promise { <pending> }.await, showUser pauses and leaves the call stack. The rest of the program carries on.fetchUser(), with id = -1. It gets its own variables.(resolve, reject) => { setTim…, with resolve = a built-in function and reject = a built-in function. It gets its own variables.setTimeout hands the callback to a timer and returns at once. It will run after 200 ms, once the call stack is empty: see Timers waiting.fetchUser returns Promise { <pending> }.fetchUser() has finished, so its variables are gone. showUser() #2 pauses at await and leaves the call stack. It will carry on when the value is ready.setTimeout callback. It gets its own variables. It can still use id from fetchUser() #1, which has already returned: the closure keeps it alive. It can still use resolve and reject from (resolve, reject) => { setTim… #1, which has already returned: the closure keeps them alive.id > 0 is true, so the if-block runs.user gets it.found Ada.setTimeout callback. It gets its own variables. It can still use id from fetchUser() #2, which has already returned: the closure keeps it alive. It can still use resolve and reject from (resolve, reject) => { setTim… #2, which has already returned: the closure keeps them alive. id goes out of scope and disappears.id > 0 is false, so the if-block is skipped.await throws the error inside showUser, and catch gets it.failed: no such user.Answer: No, just its function
Answer: A thrown error
← Promises · Errors: throw, try, catch, finally →