async and await in JavaScript
Writing asynchronous code that reads sequentially.
async function loadUser(id) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`status ${response.status}`);
}
return response.json();
}
async function main() {
try {
const user = await loadUser(7);
console.log(user.name);
} catch (error) {
console.error(error.message);
}
}
How it works
awaitpauses until the promise settles.- A non-ok response is turned into a thrown error.
try/catchhandles rejections like normal errors.
Keywords and builtins used here
asyncawaitcatchconstfunctionifreturnthrowtry
The run, in numbers
- Lines
- 16
- Characters to type
- 312
- Tokens
- 95
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 57 seconds.
Step 1 of 4 in async and await, step 6 of 19 in Promises & async.