[Asynchronous in JS-setTimeout/promise/await&async]

What is asynchronous? Why do we need async?

Asynchronous represents a non-blocking mode of operation. In programming, synchronous operation means that the program is executed step by step in sequence, and each step must wait for the completion of the previous step before proceeding to the next step.

Asynchronous operations allow the program to perform a task without waiting until the task is completed, but can continue to perform subsequent tasks. This improves the efficiency and responsiveness of the program.

Example: Imagine you are downloading a very large file. If you use the synchronous method, you must wait for the entire file to download before you can do anything else. During this process, you can't do anything else, just like you have to stay in front of the computer until the download is completed.

Using the asynchronous method, you can initiate a download request and then continue to do other things, such as continuing to browse the web, sending messages, etc. Once the file download is complete, you can be notified and then process the downloaded file. In this way, you can do other things while downloading without having to wait for the whole process. This is the characteristic of asynchronous.

In front-end development, asynchronous operations are often used to handle network requests, file reading and writing, scheduled tasks , etc. By using asynchronous operations, the response speed of the page can be improved, the user experience can be improved, and multiple tasks can be executed in parallel, thereby improving the efficiency of the program.

Common asynchronous methods, callback hell and optimization

Common ways to implement asynchronous implementation are as follows:

  1. Callback function (Callback) : A callback function is a function passed to other functions to be called after the asynchronous operation is completed. For example, you can delay execution by passing a callback function to the setTimeout function:

Example 1:

setTimeout(function() {
    
    
  // 在延时后执行的代码
}, 1000);

The anonymous function in the above code is the callback function.

Example 2:

// 回调函数
function asyncOperation(callback) {
    
    
  setTimeout(function() {
    
    
    const result = '异步操作的结果';
    callback(result);  // 在异步操作完成后调用回调函数
  }, 1000);
}

function handleResult(result) {
    
    
  console.log(result);  // 处理回调函数传递的结果
}

asyncOperation(handleResult);  // 调用异步操作并指定回调函数

What is a callback function? How did callback hell come about?

A callback function is a special function that is passed to other functions as parameters and is called when a specific event or condition occurs.
The callback function can be understood as a contract. When an asynchronous operation is completed, the system will call the callback function to notify the result of the operation or perform the corresponding operation.

  • In a broad sense, any function that is called when a specific event occurs or a condition is met can be called a callback function. It is often used in asynchronous programming to process the results of asynchronous operations or perform corresponding operations.
    Callback functions can be used in other situations as well. For example, functions that are called when certain events occur, functions that are passed as arguments to other functions, and so on.
  • In a narrow sense, a callback function usually refers to a specific form of function used in asynchronous programming.
    • In traditional JavaScript asynchronous programming, callback functions are usually passed as parameters to asynchronous functions and are called after the asynchronous operation is completed. For example, the setTimeout function accepts a callback function as a parameter and calls the function after the delay has elapsed.
    • A callback function in a narrow sense has the following characteristics:
      1) It is passed as a parameter to other functions.
      2) Called when a specific event occurs or a condition is met, usually after the asynchronous operation is completed.
      3) When called, receive corresponding data or error information according to the agreed parameter list.
      The definition of a callback function can vary depending on the specific context and context, but the above are some common characteristics.
      It should be noted that in modern JavaScript, with the emergence of asynchronous programming mechanisms such as Promise and async/await, callback functions in a narrow sense are replaced or further encapsulated to a certain extent. Therefore, when discussing callback functions, it is best to be clear about the context and context to avoid misunderstandings.

Callback functions were originally widely used to handle asynchronous operations, but as the complexity of asynchronous operations increased, Callback Hell (Callback Hell) became a widespread problem. Callback hell refers to a situation where code becomes difficult to understand and maintain when nesting multiple levels of callback functions.

  1. Promise : Promise is an asynchronous programming solution introduced in ECMAScript 6. It indicates that an asynchronous operation will eventually return a result or error. Using Promise, the results of asynchronous operations can be chained through the .then() method, and .catch() is also provided to catch exceptions.
const promise = new Promise(function(resolve, reject) {
    
    
  // 执行异步操作,根据操作结果调用 resolve 或 reject
});

promise
  .then(function(result) {
    
    
    // 处理异步操作成功的结果
  })
  .catch(function(error) {
    
    
    // 处理异步操作失败的错误
  });

The origin of Promise

In order to solve the problem of callback hell, some new mechanisms for handling asynchronous operations have emerged, the most prominent of which is Promise.
A Promise is an object used to handle asynchronous operations. It represents the eventual completion (or failure) of an asynchronous operation and the value of its result. Promises provide a more elegant way to handle asynchronous operations, avoiding the problem of callback hell.
Promise can execute the corresponding operation after the asynchronous operation is completed through the method of chain call , without nesting multiple callback functions.

Promise is an asynchronous programming mechanism proposed and promoted by the JavaScript community. It is influenced and inspired by many other programming languages ​​and frameworks. It is a proven and reliable asynchronous programming solution.

Use and encapsulation of promise in projects

The simplest way to write synchronous promises in WeChat applet. A very, very, very basic method of using promises.

However, when using Promise in a project, it is usually encapsulated to simplify use and improve maintainability.

Promises are often used when making data requests to the background. The following is a very simple encapsulation example (based on WeChat applet)

function request(url, method, data) {
    
    
  return new Promise((resolve, reject) => {
    
    
    wx.request({
    
    
      url: url,
      method: method,
      data: data,
      success: res => {
    
    
        resolve(res.data);
      },
      fail: err => {
    
    
        reject(err);
      }
    });
  });
}

// 使用示例
request('https://api.example.com/users', 'GET', {
    
    })
  .then(data => {
    
    
    console.log('请求成功', data);
  })
  .catch(err => {
    
    
    console.error('请求失败', err);
  });

Writing in actual projects will be more complicated.

  1. async/await: await/async can be regarded as syntactic sugar for Promise, and they are actually implemented based on Promise.
    By adding the async keyword before the function, you can make the function return a Promise. Use await to suspend the processing of the Promise value, waiting for the Promise to complete and return the result.

This allows asynchronous code to be written in a synchronous manner. It is also a very commonly used writing method in actual development.

async function doSomething() {
    
    
  try {
    
    
    const result = await someAsyncOperation();
    // 处理异步操作成功的结果
  } catch (error) {
    
    
    // 处理异步操作失败的错误
  }
}

doSomething();

About await&async

async means asynchronous, await is the abbreviation of async wait. async will return a promise object, and await will block the subsequent code, wait for the async promise to complete, and return the result of reslove.
Note: Because await will block the code, await must be used together with async, otherwise the browser will report an error.

To understand await&async, a more detailed and complete introduction is worth reading.

An example of how asynchronous issues are actually used in WeChat mini programs

  1. Timer (setTimeout, setInterval): Timer can be used to create asynchronous operations that are executed with delay. The setTimeout function is used to execute a function after a period of time, and the setInterval function will periodically repeat a function according to the specified time interval.
setTimeout(function() {
    
    
  // 在延时后执行的代码
}, 1000);

setInterval(function() {
    
    
  // 每隔一段时间执行的代码
}, 1000);

In addition to the above methods, there are many other methods and technologies to implement asynchrony, such as event monitoring, Fetch API, Web Workers, etc. These are different solutions selected according to specific scenarios and requirements.

reference

Detailed explanation of js Promise and async/await usage has very simple code examples for each step.
WeChat applet learning summary (async, await)

Guess you like

Origin blog.csdn.net/sinat_41838682/article/details/132585849
Recommended