Js asynchronous and Promise

The concept of asynchronous

Asynchronous (async) is a concept opposite to synchronous (Synchronous, sync) .
In the traditional single-threaded programming we studied, the running of the program is synchronous (synchronous does not mean that all steps run at the same time, but means that the steps are executed sequentially in a control flow sequence). The concept of asynchronous is a concept that does not guarantee synchronization. That is to say, the execution of an asynchronous process will no longer have a sequential relationship with the original sequence.
The simple understanding is: synchronization is executed in the order of your code, asynchronous execution is not in the order of the code, and asynchronous execution is more efficient .
The above is an explanation of the concept of asynchronous. Next, let’s explain asynchronous in a simple way: Asynchronous is to launch a sub-thread from the main thread to complete the task.

When to use asynchronous programming

In front-end programming (even the back-end is sometimes like this), when we deal with some short and fast operations, such as calculating the result of 1 + 1, it can often be completed in the main thread. As a thread, the main thread cannot accept multiple requests at the same time. Therefore, when an event does not end, the interface will not be able to handle other requests.
Now there is a button. If we set its onclick event to an infinite loop, then when the button is pressed, the entire web page will become unresponsive.
In order to avoid this from happening, we often use child threads to complete things that may take long enough to be noticed by the user, such as reading a large file or making a network request. Because the child thread is independent of the main thread, even if it is blocked, it will not affect the operation of the main thread. But the sub-thread has a limitation: once it is launched, it will lose synchronization with the main thread. We cannot determine its end. If we need to process something after the end, such as processing information from the server, we cannot merge it into the main thread. Go in.
In order to solve this problem, asynchronous operation functions in JavaScript often use callback functions to process the results of asynchronous tasks.

Commonly used asynchronous programming methods in JS include the following:

  1. Callback function : Using callback function allows us to perform corresponding operations after the asynchronous operation is completed.
function fetchData(callback) {
    
    
  // 模拟异步操作
  setTimeout(function() {
    
    
    const data = '这是从服务器获取的数据';
    callback(data);
  }, 2000);
}

// 调用 fetchData 函数,并传入回调函数来处理获取的数据
fetchData(function(data) {
    
    
  console.log(data); // 输出:这是从服务器获取的数据
});
  1. async/await : async/await is a language feature introduced in ES8 to simplify the use of Promise.
function fetchData() {
    
    
  return new Promise(function(resolve, reject) {
    
    
    // 模拟异步操作
    setTimeout(function() {
    
    
      const data = '这是从服务器获取的数据';
      resolve(data);
    }, 2000);
  });
}

// 使用async/await来处理异步操作
async function getData() {
    
    
  try {
    
    
    const data = await fetchData();
    console.log(data); // 输出:这是从服务器获取的数据
  } catch (error) {
    
    
    console.error(error);
  }
}

getData();
  1. Promise : Promise is an object introduced in ES6 for managing asynchronous operations.
function fetchData() {
    
    
  return new Promise(function(resolve, reject) {
    
    
    // 模拟异步操作
    setTimeout(function() {
    
    
      const data = '这是从服务器获取的数据';
      resolve(data);
    }, 2000);
  });
}

// 使用Promise的then方法来处理异步操作的结果
fetchData().then(function(data) {
    
    
  console.log(data); // 输出:这是从服务器获取的数据
});

Promise was mentioned above, let’s talk about promise below

JavaScript 中 Promise

Basic concepts of promise:

Promise is an object used to handle asynchronous operations. It provides a more structured and readable way to manage and organize asynchronous code. A Promise object represents an operation that has not yet been completed, but will eventually be completed, and returns a result or error message after the operation is completed.

Construct Promise

new Promise(function (resolve, reject) {
    
    
    // 要做的事情...
});

Constructor of Promise

The Promise constructor is the built-in constructor in JavaScript used to create Promise objects.
The Promise constructor accepts a function as a parameter. This function is synchronous and will be executed immediately, so we call it the starting function. The starting function contains two parameters, resolve and reject, indicating the success and failure status of the Promise respectively.
When the initial function executes successfully, it should call the resolve function and pass the successful result. When the starting function fails, it should call the reject function and pass the reason for the failure.

A Promise object can have the following three states:

  1. Pending (in progress) : Initial state, indicating that the asynchronous operation has not yet been completed.

  2. Fulfilled : Indicates that the asynchronous operation completed successfully and returned a value as the result.

  3. Rejected : Indicates that the asynchronous operation failed and an error object is returned as the reason for rejection.

The Promise object has the following important methods:

  1. then(): used to process the results of asynchronous operations. Multiple then() methods can be called in a chain. Each then() method receives the result of the previous operation as a parameter and returns a new Promise object for the next step of processing.

  2. catch(): used to handle errors in asynchronous operations. When the previous operation throws an exception or the Promise is rejected, the catch() method will capture the error and execute the corresponding processing logic.

  3. finally(): The finally() method will be executed regardless of whether the Promise object is fulfilled or rejected. Usually used to release resources or perform cleanup operations.

function fetchData() {
    
    
  return new Promise(function(resolve, reject) {
    
    
    // 异步操作
    setTimeout(function() {
    
    
      const data = '这是从服务器获取的数据';
      resolve(data); // 异步操作成功,调用resolve()方法
      // reject(new Error('获取数据失败')); // 异步操作失败,调用reject()方法
    }, 2000);
  });
}

// 使用Promise的then()方法处理异步操作的结果
fetchData()
  .then(function(data) {
    
    
    console.log(data); // 输出:这是从服务器获取的数据
  })
  .catch(function(error) {
    
    
    console.error(error); // 输出错误信息
  })
  .finally(function() {
    
    
    console.log('操作完成'); // 无论成功或失败,最终都会执行该函数
  });

In the above example, the fetchData function returns a Promise object. Specify the processing logic when the operation succeeds by calling the then() method, and specify the processing logic when the operation fails by calling the catch() method. The finally() method will be executed after the Promise is executed, regardless of success or failure.

Promises provide better control flow and error handling mechanisms, making asynchronous code easier to understand, maintain, and extend .

Promise usage scenarios

  1. AJAX request : When making an AJAX request, you can use Promise to handle asynchronous operations and obtain the server's response data. Promise can better manage the success and failure of requests and handle them accordingly.

  2. File loading : In front-end development, it is often necessary to load external files, such as images, CSS files, JavaScript files, etc. Promise can be used to manage asynchronous operations during file loading to ensure that the file is loaded successfully before subsequent operations.

  3. Dependencies of multiple asynchronous operations : Sometimes there are multiple asynchronous operations, and the result of one operation depends on the completion of another operation. Promise can handle this dependency through chain calls, making the code clearer and readable.

  4. Execute multiple asynchronous operations in parallel : In some cases, we need to execute multiple independent asynchronous operations at the same time and wait for them all to complete before continuing with subsequent processing. Promise provides the Promise.all() method to execute multiple asynchronous operations in parallel and return results after all are completed.

  5. Timeout control of asynchronous tasks : Sometimes it is necessary to control the timeout of asynchronous tasks, that is, if an asynchronous task is not completed after a certain time, it will be interrupted and processed accordingly. Promise can achieve timeout control by combining the setTimeout and Promise.race() methods.

  6. Database operations : When performing database queries or interacting with the backend, it is often necessary to use Promise to handle asynchronous operations in order to better manage the results and exceptions of database operations.

In short, whether in front-end or back-end development, as long as asynchronous operations are involved, you can consider using Promise to provide a more elegant and reliable way of writing code.

Advantages and Disadvantages of Promises

advantage
  1. Clearer asynchronous code : Promise provides a structured way to organize and process asynchronous code, making the code more readable, easy to understand and maintain. Through chain calls, multiple asynchronous operations can be connected to form a clear execution process.

  2. Better error handling mechanism : Promise can uniformly handle asynchronous operation errors through the catch() method, avoiding the callback hell problem that easily occurs in traditional callback functions. Error handling is more centralized and controllable, improving the robustness and reliability of the code.

  3. Supports parallel and serial operations : Promise can implement multiple asynchronous operations in parallel through the Promise.all() method, and wait for all of them to complete before processing the results. At the same time, you can also implement serial execution of asynchronous operations by concatenating multiple then() methods to facilitate management of dependencies between asynchronous operations.

  4. Provides richer functional extensions : In addition to basic asynchronous operation processing, Promise also provides some commonly used methods, such as finally(), race(), etc., which can achieve more functional requirements in asynchronous operations, such as resource release. , timeout control, etc.

  5. Tightly integrated with modern JavaScript syntax : Promise is part of the ES6 specification and closely integrated with other modern JavaScript syntax (such as arrow functions, async/await). This makes using Promises more convenient and also provides more options for asynchronous programming.

shortcoming
  1. The learning curve is steep : Compared with the traditional callback function method, Promise introduces some new concepts and usage methods, which requires learners to learn and adapt. Beginners may need some time to understand how Promises work and how to use them correctly.

  2. Cancellation is not supported : Once a Promise is created, it cannot cancel or interrupt the asynchronous operation being executed. Although similar effects can be achieved through some techniques, there is no official standard support, which may cause some confusion.

  3. Not supported by all browsers : Although Promise is an ES6 standard, it may not be fully supported in some older browsers. For compatibility, you may need to use polyfill or conversion tools (such as Babel) for conversion.

To sum up, Promise, as a mode and tool for handling asynchronous operations, has obvious advantages in most cases, but it is also necessary to pay attention to its scope of application and some limitations. In actual use, you can choose whether to use Promise and how to use it according to specific needs and project requirements.

Guess you like

Origin blog.csdn.net/He_9a9/article/details/132775630