Promises primarily handle asynchronous operations, confirming the completion of the asynchronous operation before executing subsequent statements.

Js is usually single threaded, and the common asynchronous operations are:

  • ajaxrequest
  • IO operation (file read)
  • The timer

The principle of asynchronous operation is as follows: After the asynchronous operation is performed, the asynchronous operation will be executed. The following statements will be directly executed before the operation is complete. After the statement is executed, the operation will be completed.

  • Common asynchronous request operations

const promise = new Promise(function(resolve, reject) { // ... Request codeifResolve (value); }else{ reject(error); }});Copy the code
  • then/catch

thenforPromiseSuccessful statement execution

promise.then(function(res){});
Copy the code

catchforPromiseFailed statement execution

promise.catch(function(err){});
Copy the code

Regular use

promise.then(function(res) {}). The catch (function(err){
    
});
Copy the code

Then abuse is also very disgusting, continuous then down. And so came up with the ultimate solution.

  • async/await

async/awaitisthen/catchA perfect version of. The functions andthen/catchSame, just difference in usage.

Every time I meet oneawaitI’m going to go back and execute. It’s a synchronous operation!

async f1(){
 const res = await promise;
}
Copy the code

You can usetry/catchListening to thePromiseReturn state,tryTo succeed,catchfailure

async f1() {
 try{
   const res = await promise;
  }catch(err){
   console.log(err)
  }
}
Copy the code