In previous interviews, it was common to be asked how to solve the asynchronous hell callback. How do I use Promise? Or can you write promises by hand? Today, I will summarize my understanding of Promise based on my previous use and my study of multiple technical blogs on the Internet.

What is a Promise

ES6 natively provides Promise objects, which represent things that will happen in the future, to pass messages about asynchronous operations. And Promise provides a unified API that allows asynchronous operations to be handled in the same way.

However, Promise has some disadvantages, including: 1. It cannot be cancelled. Once created, it is executed immediately and cannot be cancelled. 2. If the callback function is not set, the Promise will throw an error internally, but not externally. 3. When in a pending state, there is no way to know where the progress is.

Until Promise came along, this was handled by callback functions, but nested layers of callback functions could easily lead to callback hell. As follows:

    const fs = require('fs');
    fs.readFile('1.txt',(err,data)=>{
      fs.readFile('2.txt',(err,data)=>{
        fs.readFile('3.txt',(err,data)=>{
                   //....
        });
      });
    });
Copy the code

After rewriting the above code using Promise:

   const readFile = function(fileName){
      return new Promise((resolve,reject)=>{
          fs.readFile(fileName,(err,data)=>{
              if(err){
                 reject(err)
              }
              else{
                resolve(data)
              }
          })
      })   
   }
   
   readFile('1.txt').then(data=>{
      return readFile(2.txt);
   }).then(data=>{
      return readFile(3.txt);
   }).then(data=>{
      //...
   })
Copy the code

Promise specification

Es6 uses the Promise/A+ specification. Es6 also introduces promise. all, Promise,race, Promise,catch, promise. resolve, promise. reject and other methods.

The basic structure of promises

The usual use of Promise

   var fn = new Promise(function(resolve,reject){
       console.log('start');
       setTimeout(function(){
          resolve(2)
       },1000)
   })
   fn.then(function(res){
      console.log('suc',res)
   },function(err){
   console.log('err',err)
   )}
Copy the code