JavaScript Async/Await - Exercise 1
An async function always returns a promise.
async function getValue() {
return 42;
}
getValue().then(console.log);
It pauses that function until a promise settles, then gives its result.
async function read() {
const value = await Promise.resolve('ready');
console.log(value);
}
It can be used inside an async function.
async function start() {
await Promise.resolve();
}
Wrap the await expression in try...catch.
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.
const results = await Promise.all([
getUser(),
getSettings()
]);
Start both promises before awaiting their results.
const userPromise = getUser();
const postsPromise = getPosts();
const user = await userPromise;
const posts = await postsPromise;
It runs cleanup code whether the promise fulfills or rejects.
await save().finally(() => {
button.disabled = false;
});
No. It pauses only the current async function while other work can continue.
async function waitForData() {
await fetch('/data');
console.log('done');
}
Its returned promise is rejected with the thrown error.
async function fail() {
throw new Error('No access');
}
fail().catch(console.error);
It expresses asynchronous steps in a sequential style while preserving promise behavior.
async function showProfile() {
const user = await getUser();
render(user);
}