Using Await for Asynchronous Flow
script.js
index.html
This code demonstrates how the await keyword can be used inside an async function to pause execution until a Promise resolves. You start by defining an async function named fetchData. Inside this function, you create a new Promise called dataPromise, which simulates an asynchronous data fetch using setTimeout. The promise resolves with the string "Data loaded!" after one second.
The crucial line is const result = await dataPromise;. Here, the await keyword tells JavaScript to pause execution of the fetchData function until dataPromise is resolved. Once the promise resolves, the resolved value ("Data loaded!") is assigned to the result variable, and the next line (console.log(result);) is executed, printing the result to the console.
Using await in this way makes asynchronous code easier to read and write. Without await, you would need to use .then() chaining, which can quickly become hard to follow as your logic grows. With await, your asynchronous code appears more like synchronous code, improving clarity and maintainability.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Can you show me the code example for this explanation?
What happens if the promise is rejected instead of resolved?
Can you explain the difference between using `await` and `.then()` in more detail?
Awesome!
Completion rate improved to 3.57
Using Await for Asynchronous Flow
Svep för att visa menyn
script.js
index.html
This code demonstrates how the await keyword can be used inside an async function to pause execution until a Promise resolves. You start by defining an async function named fetchData. Inside this function, you create a new Promise called dataPromise, which simulates an asynchronous data fetch using setTimeout. The promise resolves with the string "Data loaded!" after one second.
The crucial line is const result = await dataPromise;. Here, the await keyword tells JavaScript to pause execution of the fetchData function until dataPromise is resolved. Once the promise resolves, the resolved value ("Data loaded!") is assigned to the result variable, and the next line (console.log(result);) is executed, printing the result to the console.
Using await in this way makes asynchronous code easier to read and write. Without await, you would need to use .then() chaining, which can quickly become hard to follow as your logic grows. With await, your asynchronous code appears more like synchronous code, improving clarity and maintainability.
Tack för dina kommentarer!