What is the execution order of async/await, promise and setTimeout?

In modern web development, asynchronous programming has become a necessary skill. In JavaScript, there are many ways of asynchronous programming, including async/await, promise and setTimeout. However, for beginners, these concepts can be a bit confusing. In this article, we'll dive into the execution order of async/await, promises, and setTimeout to help you better understand asynchronous programming.

1. Overview of asynchronous programming

In computer science, asynchronous programming refers to a programming pattern in which a program does not block while waiting for some operation to complete. This enables the program to perform other tasks while waiting for the operation to complete. Asynchronous programming is especially useful in web development because many web applications require interactions with remote servers, and these interactions can take a long time.

JavaScript is a single-threaded programming language, which means it can only execute one task at a time. This makes it especially important to do asynchronous programming in JavaScript. In JavaScript, we have a variety of ways to achieve asynchronous programming, including callback functions, promises, async/await, and setTimeout and setInterval.

Callback functions are one of the earliest asynchronous programming patterns in JavaScript. A callback function is a function that is called when an operation completes. Callback functions are very useful when dealing with asynchronous code, but they are also prone to the problem of callback hell (callback hell). Promises are one of the more modern asynchronous programming patterns in JavaScript, which allow us to better handle asynchronous code. A promise is an object that represents the result of an asynchronous operation. async/await is a promise-based asynchronous programming pattern, which allows us to write more concise asynchronous code. setTimeout and setInterval are a way to execute code after a specified time. setTimeout means to execute the code after the specified number of milliseconds, and setInterval means to execute the code repeatedly every specified number of milliseconds.

In this article, we'll focus on async/await, promises, and setTimeout, and discuss the order in which they execute.

2. The order of execution of promises

Promises are one of the most important asynchronous programming patterns in JavaScript. Promise is an object that represents the result of an asynchronous operation. It has three states: pending (in progress), fulfilled (completed), and rejected (rejected). When a Promise object is created, it is in the pending state. When the asynchronous operation completes successfully, the Promise object becomes fulfilled. If the asynchronous operation fails, the Promise object will become rejected.

The execution order of Promise objects is very important because it determines the execution order of the code. Let's look at a simple example:

let promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('Promise resolved');
  }, 1000);
});

promise.then(function(value) {
  console.log(value);
});

In this example, we create a new Promise object and resolve it to a resolved state after 1 second. We use the then() method to execute code when the Promise object is resolved. In this example, we output "Promise resolved" when the Promise object is resolved.

When we run this code, the output will be "Promise resolved". This is because the state of the Promise object has already been resolved, so the code executes immediately. If we change the code so that the state of the Promise object takes longer than 1 second to be resolved, the output will be different:

let promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('Promise resolved');
  }, 3000);
});

promise.then(function(value) {
  console.log(value);
});

In this example, we change the time of the setTimeout() function to 3 seconds. Therefore, after 3 seconds, the Promise object will be resolved. When the Promise object is resolved, we will output "Promise resolved". Therefore, the output result will be output after 3 seconds.

This example demonstrates the order in which Promises are executed. When a Promise object is created, it is in the pending state. The state of the Promise object will be resolved when the asynchronous operation completes. When the Promise object is resolved, we can use the then() method to execute code.

3. Execution order of async/await

async/await is a promise-based asynchronous programming pattern. It allows us to write more concise asynchronous code. When we use async/await, we can use the await keyword to wait for the resolution of the promise object. When the promise object is resolved, we can use the resolved value to continue executing the code. Let's look at a simple example:

async function getData() {
  let promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Data loaded');
    }, 1000);
  });

  let result = await promise;
  console.log(result);
}

getData();

In this example, we define the getData() function using an async function. In the getData() function, we create a new Promise object and resolve it to the resolved state after 1 second. We then wait for the Promise object to be resolved using the await keyword, and assign the resolved value to the result variable. Finally, we output the value of the result variable.

When we run this code, the output will be "Data loaded". This is because we use the await keyword to wait for the Promise object to be resolved and assign the resolved value to the result variable. Therefore, when the Promise object is resolved, we will output "Data loaded".

The execution order of async/await is very important because it determines the execution order of the code. When we use the await keyword to wait for the Promise object to be resolved, the code will be blocked. This means that the code after the await keyword will not be executed until the Promise object is resolved. Therefore, we should carefully consider where to use the await keyword to ensure that our code will work properly.

Fourth, the execution order of setTimeout

setTimeout is one of the most common timer functions in JavaScript. It allows us to execute a piece of code after a certain period of time. When we call the setTimeout() function, it defers the execution of the code until a certain amount of time. Let's look at a simple example:

console.log('Start');
setTimeout(function() {
  console.log('Hello');
}, 1000);
console.log('End');

In this example, we output "Start" to the console, then call the setTimeout() function and set the timer time to 1 second. Finally, we print "End" to the console.

When we run this code, the output will be "Start", "End", and then "Hello". This is because we output "Start" on the console, then call the setTimeout() function, and set the timer time to 1 second. Therefore, the JavaScript engine will defer execution of the code in the setTimeout() function until 1 second later. During this 1 second, the JavaScript engine will continue to execute subsequent codes, that is, output "End". When 1 second has elapsed, the JavaScript engine will execute the code in the setTimeout() function, which outputs "Hello".

The execution order of setTimeout is very important, because it can affect the performance and responsiveness of the program. If we set a timer time that is too long, the program may become slow. On the other hand, if we set a timer time that is too short, the program may become unstable. Therefore, we should carefully consider where to use the setTimeout() function and set an appropriate timer time to ensure that the program can run normally.

5. Execution order of async/await, Promise and setTimeout

Now that we understand the execution order of async/await, Promise, and setTimeout, let's look at a more complex example to gain insight into how they are related.

async function getData() {
  let promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Data loaded');
    }, 3000);
  });

  let result = await promise;
  console.log(result);
}

console.log('Start');
getData();
console.log('End');

In this example, we define an async function getData() that creates a new Promise object and resolves it to the resolved state. We use the await keyword to wait for the Promise object to be resolved and assign the resolved value to the result variable. Finally, we output the value of the result variable to the console.

In the main function, we output "Start" to the console, and then call the getData() function. Finally, we print "End" to the console.

When we run this code, the output will be "Start", then "End", and finally "Data loaded". This is because we print "Start" to the console and then call the getData() function. In the getData() function, we create a new Promise object and resolve it to the resolved state. Then, we wait for the Promise object to be resolved using the await keyword, and assign the resolved value to the result variable. During this time, the JavaScript engine stops executing code until the Promise object is resolved. When the Promise object is resolved, the JavaScript engine will continue to execute the code and output the value of the result variable "Data loaded". Finally, we print "End" to the console.

In this example, async/await, Promise and setTimeout are executed in the following order:

  1. In the main function, we print "Start" to the console.

  2. We call the getData() function, and enter that function.

  3. In the getData() function, we create a new Promise object and resolve it to the resolved state. Then, we wait for the Promise object to be resolved using the await keyword, and assign the resolved value to the result variable. During this time, the JavaScript engine stops executing code until the Promise object is resolved.

  4. After the time (3 seconds) set in the setTimeout() function has elapsed, the Promise object is resolved and the resolved value is passed to the result variable.

  5. The JavaScript engine continues to execute the code and outputs the value "Data loaded" of the result variable.

  6. In the main function, we print "End" to the console.

Therefore, the execution order of async/await, Promise and setTimeout is very important. If we don't set the order of execution of Promise objects or timer functions correctly, our program may bug or become slow. Therefore, we should carefully consider where to use async/await, Promise, and setTimeout to ensure that the program will work properly.

6. Summary

In this article, we introduced three JavaScript functions async/await, Promise and setTimeout, and discussed their relationship and execution order. We learned that async/await is a syntactic sugar for using Promises, which allows us to use simpler code to handle asynchronous operations. Promise is a powerful tool for handling asynchronous operations in JavaScript, which provides a way to convert asynchronous operations into synchronous operations. setTimeout is a function that allows us to execute a piece of code after a certain period of time. It can be used to handle simple timers and animation effects.

In JavaScript, we usually use these functions to handle asynchronous operations and ensure that the program runs properly. We should pay attention to the execution order between them and use them reasonably when needed. When using async/await, Promise, and setTimeout, we should use best practices as much as possible and follow some rules to ensure code readability, maintainability, and scalability.

Therefore, understanding the execution order of async/await, Promise, and setTimeout is very important for developing high-quality JavaScript programs. I hope this article can help you better understand the relationship between them and use them more proficiently in your daily development.

Guess you like

Origin blog.csdn.net/tyxjolin/article/details/130176285