reference

  • Ruan Yifeng ES6 Promise object
  • Promise A + specification

A Brief description of Promise

meaning

  • Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. It was first proposed and implemented by the community, and ES6 has written it into the language standard, unifying usage, and providing Promise objects natively.
  • A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way.

Simply put, a promise is a promise that will be fulfilled in the future. For example, daughter-in-law, when I have money to buy you a bag, wait first, give you a promise, and then buy when I have money. Commitment is a waiting state. You can set success or failure, buy package and don’t buy package. These are the three states described below.

The characteristics of

  • The status of an object is not affected. The Promise object represents an asynchronous operation with three states: Pending (in-progress), equivalence (success), and Rejected (failure).
  • Once the state changes, it never changes. There are only two possibilities: from pending to depressing and from pending to Rejected.

Simply put, the Promise object has three states: once it succeeds, it cannot fail; once it fails, it cannot succeed

The main solution to the callback hell, function nesting problem

  • For example, look at the code below
let fs = require("fs");
fs.readFile("a.txt".'utf8'.function(data1){ 
    fs.readFile("b.txt".'utf8'.function(data2){ console.log(data1,data2); })})Copy the code

When data2 data needs to depend on the last return data1, this can cause a nesting problem. If the nesting continues indefinitely, this can cause a callback hell problem

Basic use of Promise

Create a Promise instance

  • Promise itself is a constructor that requires us to create an instance, pass a function as an argument (we call it executor), and accept two arguments resolve(success) and reject(failure)
letP =new Promise((resolve,reject)=>{// The executor will be called by default on new, immediately execute console.log("1")
    resolve("123"// Resolve, pass 123});Copy the code

So what does that do? Let’s look at the then method of P and how do we get 123

Then chain

  • Then passes two functions, the first corresponding to a success callback (resolve(‘123’)) and the first corresponding to a failure callback (reject(‘123’)).
  • Then 123 in resolve(‘123’) is captured by a successful callback, while passing reject(‘123’) is captured by a failed callback
Console. log(value)},err=>{// error =>{// error =>{ Reject Console.log (err)}).then(value=>{console.log(value)},err=>{console.log(err)})Copy the code
  • Remember how we solved the nesting problem with promise
let fs = require('fs');
function read(file){
    return new Promise(function(resolve,reject){
        fs.readFile(file,'utf8'.function(err,data){
            if (err) {
                returnreject(err); } resolve(data); })})}read('./a.txt').then(function(data){
    return read('./b.txt');
}).then(function(data){
    console.log(data);
})
Copy the code
  • The above writing method is not more flow sense
  • Then can also penetrate, what does that mean, directly into the code
let Promise = require('./Promise');
let promise = new Promise((resolve,reject)=>{
  resolve('hello'); }); Promise.then ().then().then().then(data=>{// can be infinitethen, but the result is still console.log(data); //'hello'
},err=>{
  console.log('err',err);
})

Copy the code

Error handling catch

  • Catch catches an error, like a try/catch statement
p.then().then().catch(err=>{
    console.log(err)
})
Copy the code

Promise.all()

  • Proise.all() is a callback that is executed after all asynchronous operations have been performed, and takes an array in which each item should be an instance of a Promise. Promise.all() returns a promise, so it’s ok
let fs = require("fs");
function read(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8'.function(err, data) {
      if (err) return reject(err);
      resolve(data);
    });
  });
}
Promise.all([read("1.txt"), read("2.txt")]). Then (/ / canthenPromise.all() returns the same result: Promise data => {console.log(data); / / [1. TXT, 2. TXT content]}, err = > {the console. The log (err); });Copy the code

Promise.race()

  • The usage is similar to promise.all (), referring to who runs fast and whose callback executes.
let fs = require("fs");
function read(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8'.function(err, data) {
      if (err) return reject(err);
      resolve(data);
    });
  });
}
Promise.all([read("1.txt"), read("2.txt")]). Then (/ / canthenPromise.all() returns the same result: Promise data => {console.log(data); / / [1. TXT or 2. TXT content]}, err = > {the console. The log (err); });Copy the code

Reading this, I believe that you should have A general understanding of promise, the next chapter leads you to write A set of code that meets the Promise A+ specification.