What is asynchronous, synchronous, setTimeout, Promise, async

Asynchronous and Synchronous are concepts about the order in which code is executed.

Synchronization means that the code is executed line by line in order, and the next line of code is executed after each line of code is executed. The execution of synchronous code is blocked, that is, the next line of code can only be executed after the execution of the current code is completed.

Asynchronous means that the code is not executed in order, but the following code is executed first, while the code following the current code continues to execute. The execution of asynchronous code is non-blocking, that is, you can continue to execute the following code without waiting for the execution of the current code to complete.

setTimeout is a function provided in JavaScript that can execute a callback function after a specified time. It is an asynchronous operation, that is, the code will continue to execute without waiting for the time in setTimeout to expire.

Promise is an object in JavaScript used to represent a delayed completion of the operation. It can be used to handle asynchronous operations, through which you can better manage and control asynchronous code. Promise supports chain calls, you can use the then method to handle the successful operation, and use the catch method to handle the failed operation.

async/await is a syntactic sugar introduced in ES2017 to simplify the use of Promise. Use the async keyword to define an asynchronous function, use the await keyword to wait for the completion of a Promise object, and assign the result to a variable. In an async function, you can handle asynchronous operations as if you were writing synchronous code.

for example:

1. Example of synchronous code:

console.log("Start");
console.log("Hello");
console.log("End");
// Output:
// Start
// Hello
// End

This code is executed in sequence, and the output is "Start", "Hello", "End".

2. Example of asynchronous code:

console.log("Start");
setTimeout(() => {
  console.log("Hello");
}, 2000);
console.log("End");
// Output:
// Start
// End
// Hello (after 2 seconds)

In this code, setTimeout is an asynchronous operation, and the code will continue to execute without waiting for 2 seconds, so "Start" is output first, and then "End" is output. When 2 seconds have passed, the callback function in setTimeout will be executed and "Hello" will be output.

3. Promise example:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data fetched successfully");
    }, 2000);
  });
}

fetchData().then(data => {
  console.log(data);
}).catch(error => {
  console.log(error);
});
// Output (after 2 seconds):
// Data fetched successfully

In this code, the fetchData function returns a Promise object representing an asynchronous operation. In the callback function of the Promise object, use setTimeout to simulate an asynchronous operation, call the resolve method after 2 seconds, indicating that the operation is successful, and pass the data to the then method. In the then method, print out the data. If the operation fails, the reject method is called, and the error is handled in the catch method.

4. Example of async/await:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data fetched successfully");
    }, 2000);
  });
}

async function getData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

getData();
// Output (after 2 seconds):
// Data fetched successfully

In this code, the getData function is defined as an asynchronous function, which waits for the completion of the Promise object returned by the fetchData function through the await keyword. In the try block, print out the data. If the operation fails, an error is thrown, and the error is then handled in the catch block.

To sum up, synchronous code is executed line by line in order, and asynchronous code is executed out of order and will not block the execution of subsequent code. setTimeout is used to delay the execution of code, Promise is used to handle asynchronous operations, and async/await is used to write asynchronous code more conveniently.
 

Guess you like

Origin blog.csdn.net/weixin_39273589/article/details/132604720