![]() The issue here is that JavaScript is a single-thread event-based model language. Instead, it will continue and log the output “Done!” to the console, and when the request returns a couple of hundred milliseconds later, it will output the statements one by one. When the JavaScript interpreter encounters the async function, it will not wait for the request to complete. This is because logging the statements here is an asynchronous operation in JavaScript. That is the way of handling the async code in JavaScript. You see the problem, and the Done is logged first, even if we have written in the last. So, for one second, the function goes to sleep, and after the promise is resolved, it will log the next time the same string, and then again goes to sleep for 1 second, and so on.ĭone! Yello, D'oh Yello, D'oh Yello, D'oh Yello, D'oh ![]() The task() function logs the Yello and D’oh values within 1 second. We defined an array list that can help create a loop. The keyword “ await” makes JavaScript wait until that promise settles and returns its result. Before a function, the word “ async” means one simple thing: a function always returns a promise. Here, we used async-await because sleep() will return the promise. In our code, that specific function is the task(). So, we will use the sleep() function in the task() function to sleep. Then, we will call the sleep() function when we need to sleep the specific function. In this example, first, we have defined a sleep function.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |