Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.


One, foreword

The last one, completed the Promise source code learning directory;

In this paper, the Promise is introduced briefly.


Two, Promise brief introduction

  • A Promise is a class or constructor that is provided natively by JS to perform the expected asynchronous task processing by instantiating the Promise;
  • A Promise is an object that gets asynchronous action messages; A promise that results will be returned after a certain period of time;
  • Promises are an asynchronous programming solution, listed as a formal specification in ES6, that provides native Promise objects;
  • A Promise can accept an asynchronous request and get the result of that request in the provided then/catch methods.
  • Promise supports chained calls, which allow the results of asynchronous requests to be processed synchronously.

Three, the basic use of Promise

Use Promise to wrap asynchronous operations:

/ / create
var promise = new Promise((resolve, reject) = >{
  setTimeout(() = >{
    if("Asynchronous request successful"){
      resolve('ok');
    } else {
      reject('error')}},2000);
});

/ / use
promise.then(data= >{
  console.log(data);
}).catch(error= >{
  console.log(error);
});
Copy the code

As you can see from the example:

  • The Promise argument is a callback that takes two arguments: resolve and reject;
  • When the asynchronous operation succeeds, the call to resolve returns the result of the success of the asynchronous operation.
  • When an asynchronous operation fails, reject is called to return the failure result of the asynchronous operation.
  • If the asynchronous operation succeeds, then processes subsequent operations.
  • If the asynchronous operation fails, catch is entered to process subsequent operations. (In the current example, failed operations can also be caught when the second callback of the THEN function is defined, a mechanism explained later.)

But in fact, in addition to the above examples, promises have more features, and understanding and mastering these features is the foundation of good use of promises;


Fourth, compare Promise and callback

Callback handles asynchronous operations:

function async(callback){
    setTimeout(function(){
        callback("Asynchronous operation complete");
    }, 1000);
}

async(function(data){
    console.log(data);
});
Copy the code

The essential difference between promises and callback is inversion of control;

  • In callback mode, the execution control of the callback function is at the encapsulation layer:

    • The business layer passes the callback function definition to the encapsulation layer;
    • The wrapper layer executes the callback function at the end of the task;
    • The business layer does not invoke the callback function, nor does it even see the calling code;
  • In the Promise pattern, execution control of the callback function is at the business level:

    • The business layer does not pass the callback function directly to the encapsulation layer (inside the Promise object);
    • At the end of the task, the encapsulation layer does not know the callback to be executed. It can only notify the business layer through resolve or reject, and the business layer controls the callback execution in THEN () or Reject ().
    • The business layer can not only see the calling code of the callback function, but also modify it;

Five, the role of promises

Promises were created (mostly) to address asynchronous processing in programs;

  • Promise not only solved the “callback hell” problem of multiple layers of nesting of asynchronous callbacks;
  • More importantly, Promise offers a more complete and powerful asynchronous solution; Support bulk Promise operations through the methods provided on the Promise constructor, such as: All, Race, any, allSettled, etc.

Six, the importance of Promise

At present, Promise is almost ubiquitous in front-end applications and has become one of the most important skills in front-end development.

Promise is also a frequent research point for front-end interviews: the investigation methods are diversified, and the investigation content can be deep or shallow; At the same time, it can also be associated with many practical application scenarios; Therefore, mastering Promise is a must for every front-end development;


Seven, Promise compatibility

1. Compatibility

Promise belongs to ES6 specification content, browser support Can I use or MDN:

  • Chrome – Supported
  • 360 browser – compatible mode supported
  • Internet Explorer kernel browser – Not supported

2. Solutions

  • bluebird.js

Use Promsie objects in your project, and you can use bluebird.js as a third-party plugin.

Bluebird encapsulates ES6 native Promise to solve browser compatibility problems;

  • es6-promise

Using ES6-Promise can also solve the problem of not supporting promises under IE;


Eight, Promise use scenarios

Asynchronous processing of JS is ubiquitous. For example, NodeJS and applets provide apis based on callbacks.

This often leads to the bad taste of “callback hell” in development (the team’s CodeReview concerns) :

const fs = require('fs');

fs.readFile('./a.txt'.'utf8'.(err,data) = >{
  if(err) return err
  console.log(data)
  fs.readFile('./b.txt'.'utf8'.(err,data) = >{
    if(err) return err
    console.log(data)
    fs.readFile('./c.txt'.'utf8'.(err,data) = >{
      if(err) return err
      console.log(data)
      fs.readFile('./d.txt'.'utf8'.(err,data) = >{
        if(err) return err
        console.log(data)
        / /... The callback hell})})})})Copy the code

Promise was born as a solution to asynchronous front-end programming in order to solve the problem of asynchronous operations like this and make writing code more elegant and readable.

The code above uses Promise wrapping as follows:

const fs = require('fs');

// Use the Promise wrapper to process fs.readfile
function readFile(filePath, encoding) {
  return new Promise((resolve, reject) = > {
    fs.readFile(filePath, encoding, (err, data) = > {
      if (err) return reject(err) / / fail
      resolve(data) / / success})}); }// The usage mode
readFile('./a.txt'.'utf8').then((data) = > {
  console.log(data)
  return readFile('./b.txt'.'utf8')
}).then((data) = > {
  console.log(data)
  return readFile('./c.txt'.'utf8')
}).then((data) = > {
  console.log(data)
  return readFile('./d.txt'.'utf8')
}).then((data) = > {
  console.log(data)
})
Copy the code

This approach of wrapping asynchronous callbacks as promises (also known as Promisify) is commonly used in NodeJS, applets scenarios to make asynchronous code more compact.

  • Remark:

When using a class library, check the official instructions carefully. Many of the current class libraries support returning Promise instances, so try to avoid repeated packaging externally. Some libraries support both callback and Promise forms;


Nine, Promise advantages and disadvantages

  • advantages

    • Optimize asynchronous code to solve the problem of “callback hell” and improve the readability and maintainability of code;
    • Promise objects provide a unified interface that makes it easier to control asynchronous operations;
    • The catch method is used to capture and process the exception uniformly.
  • disadvantages

    • There is no way to cancel promises, which are executed as soon as they are created and cannot be cancelled halfway through;
    • If no callback function is set, errors thrown from within a Promise are not reflected externally;
    • When in the Pending state, there is no way to know which stage of progress is currently being made (just started or nearly completed).

Ten, the end

This article briefly introduces Promise, mainly involving the following points:

  • Promise introduction and basic use;
  • Promise vs. callback;
  • The importance and role of promises;
  • Promise usage scenarios: Promisify encapsulation;
  • Promise’s advantages and disadvantages, compatibility;

Note: The positioning of this paper is only a simple understanding and understanding of Promise, without in-depth introduction and analysis, such as: Promise state, execution order, chain call, API use, exception handling, etc.;

In the next chapter, I will introduce the relevant functions and feature analysis of Promise with examples.


Maintain a log

  • 20211019
    • Update part of the sample code, more in line with the relevant knowledge points;
    • Add the Promise compatibility section;
    • Update the ending and abstract of the article;
  • 20211024
    • Expanded part of the content;
  • 20211025
    • Reorganize the outline, adjust the first and second level titles, expand the relevant content;
    • Revise the title and abstract of the article;