JavaScript Async/Await - Exercise 1
An async function always returns a promise. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
async function getValue() {
return 42;
}
getValue().then(console.log);
It pauses that function until a promise settles, then gives its result. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
async function read() {
const value = await Promise.resolve('ready');
console.log(value);
}
In classic script code, await can be used only inside an async function. Modules also support top-level await. That lets later code use the value without manually nesting Promise callbacks.
async function start() {
await Promise.resolve();
}
Wrap the await expression in try...catch. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
async function load() {
try {
await getData();
} catch (error) {
console.error(error);
}
}
It waits for multiple promises and resolves with all results, or rejects if one fails. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
const results = await Promise.all([
getUser(),
getSettings()
]);
Start both promises before awaiting their results. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
const userPromise = getUser();
const postsPromise = getPosts();
const user = await userPromise;
const posts = await postsPromise;
It runs cleanup code whether the promise fulfills or rejects. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
await save().finally(() => {
button.disabled = false;
});
No. It pauses only the current async function while other work can continue. That lets later code use the value without manually nesting Promise callbacks.
async function waitForData() {
await fetch('/data');
console.log('done');
}
Its returned promise is rejected with the thrown error. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
async function fail() {
throw new Error('No access');
}
fail().catch(console.error);
It expresses asynchronous steps in a sequential style while preserving promise behavior. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.
async function showProfile() {
const user = await getUser();
render(user);
}