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.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion
Awesome!
Completion rate improved to 3.57
Using Await for Asynchronous Flow
Glissez pour afficher le menu
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.
Merci pour vos commentaires !