Home  >  Article  >  Web Front-end  >  What are the two asynchronous processing methods in JavaScript?

What are the two asynchronous processing methods in JavaScript?

青灯夜游
青灯夜游Original
2022-01-27 16:54:282031browse

Two asynchronous processing methods in JavaScript: 1. Use "Promise" to handle asynchronous, which can help manage the code returned by asynchronous methods; 2. Use "async/await" to handle asynchronous, which can be used to handle asynchronous Events are handled using synchronous syntax.

What are the two asynchronous processing methods in JavaScript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript’s asynchronous processing method

Promise

(1) promise object It is a specification and a pattern proposed by the commonJS working group, with the purpose of providing a unified interface for asynchronous programming.

(2) Promise is a pattern. Promise can help manage the code returned asynchronously. He encapsulates the code and adds a management layer similar to event handling. We can use promises to register code that will run after the promise succeeds or fails.

(3) After the promise is completed, the corresponding code will also be executed. We can register any number of functions to run on success or failure, and we can register event handlers at any time.

(4) Promise has two states: 1. Waiting (pending); 2. Completed (settled).

Promise will remain in a waiting state until the asynchronous call it wraps returns/times out/ends.

(5) At this time, the promise status becomes completed. The completion status is divided into two categories: 1. Resolved; 2. Rejected.

(6) promise resolved (resolved): means it ends successfully. Promise rejected (rejected) means that it did not end successfully.

//promise
var p=new Promise(function(resolved))
//在这里进行处理。也许可以使用ajax
setTimeout(function(){
   var result=10*5;
   if(result===50){
      resolve(50);
   }else{
     reject(new Error('Bad Math'));
  }
},1000);
});
p.then(function(result){
    console.log('Resolve with a values of %d',result);
});
p.catch(function(){
   console.error('Something went wrong');
});

(1) The key to the code lies in the call to setTimeout().

(2) The important thing is that he called the functions resolve() and reject(). The resolve() function tells the promise user that the promise has been resolved; the reject() function tells the promise user that the promise failed to complete successfully.

(3) There are also some codes that use promise. Pay attention to the usage of then and catch. You can think of them as handlers for onsucess and onfailure events.

(4) The clever thing is that we separate promise processing from state. In other words, we can call p.then (or p.catch) as many times as we want, regardless of the state of the promise.

(5) Promise is the standard way of managing asynchronous code in ECMAscript 6. The JavaScript library uses promise to manage ajax, animation, and other typical asynchronous interactions.

Simply put, the idea is: each asynchronous task returns a promise object, which has a then method that allows a callback function to be specified. For example, the callback function f2 of f1 can be written as:

f1.then(f2);

f1 should be rewritten as follows (implemented using jquery):

function f1(){
   var dfd=$.deferred();
   settimeout(function(){
     //f1的任务代码
     dfd.resolve();
  },500);
  return dfd.promise;  
}

The advantages of writing like this: the callback function is written in a chain style. The flow of the program can be seen clearly, and there is a complete set of supporting methods that can realize many powerful functions.

For example, specify multiple callback functions

f1().then(f2).then(f3);

Another example, specify the callback function when an error occurs:

f1().then(f2).fail(f3);

Moreover, it has one that none of the previous three methods have. Advantages: If a task has been completed and a callback function is added, the callback function will be executed immediately.

So you don’t have to worry about missing an event or signal.

Disadvantages of this method: It is relatively difficult to write and understand.

async await

Since the advent of ES6 Promise, asynchronous code has gradually changed from callback hell to elegant functional pipeline processing, but for For developers who are not familiar with it, it just changes from callback hell to Promise hell.

The new async/await is standardized in ES8. Although it is just syntactic sugar for combining Promise and Generator Function, it is passed through async/await Then asynchronous events can be processed with synchronous syntax, just like an old tree blooming new flowers. The writing style is completely different from Promise:

function wait(time, fn) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('wait:', time)
      resolve(fn ? fn() : time)
    }, time)
  })
}
await wait(500, () => console.log('bar'))
console.log('foo')
// wait: 500
// bar
// foo

By setTimeout is packaged into a Promise and then called with the await keyword. You can see that the result will be synchronously executed first bar and then foo , that is, writing asynchronous events into synchronous processing mentioned at the beginning.

Look at another example:

async function withAsyncAwait() {
  for(let i = 0; i 3402058288807f50677058ab1f5894f3 console.log(i))
  }
}await withAsyncAwait()
// wait: 0
// 0
// wait: 500
// 1
// wait: 1000
// 2
// wait: 1500
// 3
// wait: 2000
// 4

The code implements the withAsyncAwait function, using the for loop and the await keyword Execute the wait function repeatedly; when executed here, the loop will wait for a different number of seconds in sequence before executing the next loop.

When using async/await, since the await keyword can only be executed in async function, be sure to remember to use it at the same time .

In addition, when using loops to process asynchronous events, you need to note that many Array methods provided after ES6 do not support the async/await syntax. If ## is used here #forEach replaces for, the result will be synchronous execution, and numbers will be printed every 0.5 seconds:

[Related recommendations:

javascript learning tutorial

The above is the detailed content of What are the two asynchronous processing methods in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn