Complete the code to create a function that returns a promise.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data loaded'), [1]);
});
}The number 1000 means 1000 milliseconds (1 second) delay before resolving the promise.
Complete the code to use async function syntax.
async function [1]() {
const result = await fetchData();
console.log(result);
}The function name can be anything, but here we choose 'loadData' to show an async function that waits for data.
Fix the error in the code by adding the missing keyword.
async function load() {
const data = [1] fetchData();
console.log(data);
}The 'await' keyword is needed to wait for the promise to resolve inside an async function.
Fill both blanks to correctly handle the promise result.
async function getData() {
try {
const result = [1] fetchData();
console.log([2]);
} catch (error) {
console.error(error);
}
}Use 'await' to wait for the promise, and then log the variable 'result' that holds the data.
Fill all three blanks to create an async function that fetches data and handles errors.
async function fetchAndProcess() {
try {
const [1] = [2] fetchData();
console.log([3]);
} catch (err) {
console.error('Error:', err);
}
}We declare a variable 'data', use 'await' to wait for the promise, and then log 'data'.