当前位置:网站首页>Simply understand the promise of ES6

Simply understand the promise of ES6

2022-07-06 13:50:00 Ling Xiaoding

Simple understanding ES6 Of Promise



Preface

  1. Promise Is a solution to asynchronous programming : Grammatically speaking ,promise It's an object , From it you can get messages for asynchronous operations ; From the original point of view , It's a promise , Promise that it will give you a result after a period of time

  2. Promise It can ensure that asynchronous requests become executed sequentially

  3. Concept :Promise yes ES6 New grammar in , Itself a constructor ; Every new Coming out Promise Instance object , Both represent an asynchronous operation

  4. effect : Solved the problem of callback hell ( That is, asynchronous nested calls )
    Back to hell : Refers to the callback function , The code form of nested callback function ; If the nesting level is very deep , It's hell ;
    Callback hell is not conducive to code reading 、 Maintenance and later expansion


Promise How to use it?

  1. Create specific asynchronous operation objects
const p = new Promise(function(successCb, errorCb){
    
	//  In this  function  Define specific asynchronous operations in 
	// successCb Successful callback 
    // errorCb Failed callback 
})
  1. Promise It's a constructor , Sure new An object , Itself is an asynchronous operation
  2. Promise Of then Method
    Promise There are two method parameters when using successCb,errorCb Respectively represents the success or failure of execution
    Promise Objects can pass through then Method pair successCb and errorCb To call

There are two specific situations as follows :

result.then(function(data){
    /* Successful callback */},function(data){
    /* Failed callback */})
result.then(function(){
    /* Successful callback */}).catch(function(data){
    /* Failed callback */})

In the former then Method accepts successCb and errorCb Callback function
The latter passes then and catch The two methods accept successCb and errorCb Callback function

  1. example :
//  introduce fs modular 
const fs = require('fs')

// 4) Promise Intervene and enrich the operation ( Join the success  、 Failed callback )
function getFileCont(filename) {
    
  //  Instantiation Promise object , Used to indicate asynchronous operation 
  // new Promise(function(successCb function , errorCb function ){})
  // successCb: The current asynchronous operation is ok In this case, the execution is triggered resolve
  // errorCb: An error occurred in the current asynchronous operation ( exceeding one's expectations ) Next trigger execution reject
  return new Promise(function(successCb, errorCb) {
    
    //  Embody asynchronous process 
    fs.readFile(filename, 'utf8', function(err, data) {
    
      if (err) {
    
        return errorCb(' An error occurred while reading the file :' + err)
      }
      //  All operations are ok Normal handling in case , Give the processed results to resolve call ( return )
      successCb(data)
    })
  })
}
//  The following can guarantee   In order   Get the results 
getFileCont('./files/1.txt').then(function(result) {
    
  console.log(result)
  return getFileCont('./files/2.txt')
}).then(function(result){
    
  console.log(result)
  return getFileCont('./files/3.txt')
}).then(function(result){
    
  console.log(result)
}).catch(function(err){
    
  console.log(err)
})

ES7 Of async and await

  1. ES7 Medium async and await Can be simplified Promise call , Improve Promise Code reading and understanding
  2. async and await Combine , It can make the asynchronous call not return Promise, And just put then Parameters of parameter method ( It's also successCb function arguments ) Come back , Make code more frugal , Improve code development efficiency , It can also ensure the sequential execution of asynchronous calls
  3. asyncawait Various use cases :

Be careful :
async and await Must appear at the same time
One async Can correspond to multiple await
await The result of modification must be Promise object

var obj = {
    
  async getInfo(){
    
    await getXXXX()
    await getXXXX()
  }
}
 or 
function ffff(){
    
    // async It needs to be set to Promise The nearest outer layer of the object function In front of 
  getInfo(async function(){
    
 		await getXXXX()
      	//console.log(getXXXX())
  })
}
 or 
async function XXXX(){
    
  await getXXXX()
}

summary

  1. new Promise() Instantiate objects , The parameter callback function will have two callbacks successCb and errorCb Parameters
  2. These two callbacks can be through then and catch() Receive , But the asynchronous calling code is more or less reflected in the degree of hell callback
  3. async and await combination , The return of Promise Directly into successCb Arguments of , Greatly simplifies the complexity of code development , Improve development efficiency
  4. If necessary , adopt try/catch capture async and await
  5. Usually use ,asyncawait abnormal The solution of asynchronous sequential execution provided by the combination of three technologies
async function getThreeFile(){
    
  try{
    
    console.log(await getFileCont('./files/1.txt')) 
    console.log(await getFileCont('./files/2.txt')) 
    console.log(await getFileCont('./files/3.txt')) 
  }catch(err){
    
    console.log(err)
  }
}
getThreeFile()
原网站

版权声明
本文为[Ling Xiaoding]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916580115.html