async and await
async functions return promises. await pauses until a promise settles. Use try catch for errors.
Example
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
await wait(10);
try { await Promise.reject(new Error("bad")); }
catch (e) { console.log("caught", e.message); }
console.log(await Promise.all([1, 2].map(async (x) => x * 2)));
}
main();Result
caught bad [ 2, 4 ]
Exercise
Pause for a promise.
wait(10)Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.