Write an async function called waitAndLog that waits 2 seconds using a Promise, then logs "Done waiting".
Async/Await is a modern syntax for working with asynchronous code that makes it easier to read and write.
Mark a function with async
to enable the use of await
inside it. await
pauses the execution until a Promise resolves.
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function asyncExample() {
console.log("Start");
await delay(1000);
console.log("One second later");
}
asyncExample();
This code logs "Start", waits 1 second, then logs "One second later".
Use try/catch
blocks inside async functions to handle errors.
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}