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

In the previous article, I introduced Promise briefly, mainly covering 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;

In this paper, we will introduce the relevant functions and feature analysis of Promise with examples.

Remark:

  • This article continues to be updated to cover most of Promise’s basic features and features;
  • The more complex interview questions will be sorted out and summarized at the end of the column.

Second, basic features of Promise

Class 1, Promise

  • Promise can create objects with new, indicating that it is a class or constructor;
  • When you use promises, you pass in an executor executor;
  • The executor executor takes arguments reslove and reject.
  • Introduces the Executor executor;
  • Reslove and Reject;

2. executor executor

Code examples:

new Promise(() = >{ // executor executor
  console.log('promise')})console.log('ok')

// Execution result:
promise
ok
Copy the code
  • Symptoms: Output promise first, then output OK;
  • So, the executor executor is executed immediately after a Promise is created;
  • The executor executor is introduced. Is implemented immediately after a Promise is created;

3. Three states of Promise

Promises have three states:

  • Pending: Pending state (default);
  • This is a pity.
  • Rejected: indicates the failed state.

Code examples:

let promise = new Promise(() = >{
  console.log('promise')})console.log('ok', promise)

// Execution result:
promise
ok Promise { <pending> }
Copy the code
  • The Promise state defaults to pending:
  • The Promise state can be changed (only once) by calling reslove or Reject;
  • Three states of Promise are introduced.
  • The relationship between reslove, Reject and Promise states is introduced.

4. Role of Reslove and Reject

The executor executor functions reslove and Reject describe the Promise state:

  • 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.

reslove

  • This is a pity that the current Promise state will change to a successful state by calling the reslove function.
  • Resolve indicates success, and a value can be passed.

Example:

let promise = new Promise((resolve, reject) = >{
  console.log('promise')
  resolve("Success");	// Call the resolve method
})
console.log('ok', promise)

// Execution result:
promise
ok Promise { 'success' }
Copy the code

reject

  • Reject: Change the current Promise state to rejected by calling reject.
  • Reject indicates failure. You can pass in a reason.

Example:

let promise = new Promise((resolve, reject) = >{
  console.log('promise')
  reject("Failure");	// Call reject
})
console.log('ok', promise)

// Execution result:
promise
ok Promise { <rejected> 'failure' }
Copy the code
  • Reslove and reject are introduced: call and pass arguments;
  • The corresponding relationship between reslove, Reject and Promise states is introduced.

5. The state of a Promise instance can only change once

Code examples:

let promise = new Promise((resolve, reject) = >{
  console.log('promise')
  throw new Error("Throw an error");
  resolve();  // If resolve fails, the state will not change
})
promise.then((value) = >{
  console.log('success', value) 
},(reson) = >{
  console.log('err',reson)
})
console.log('ok')

// Execution result:
promise
ok
err Error: Throws an errorCopy the code

Once the state of a Promise instance changes, it cannot be changed again:

  • The promise state can only be updated from pending to depressing success or from pending to Rejected failure.
  • When a PROMISE is in a successful or failed state, the state of the current Promise instance cannot be changed again by calling resolve, Reject, or throwing an exception.

The example uses promise.then(), which is covered in more detail below;

6, Promise API

Like most “class classes,” the Promise API falls into two broad categories:

  • Instance API or prototype methods: instance methods that must be new to use;
  • Static API or class methods: static methods that can be used without requiring new instances;

Which respectively contain the following methods:

  • There are three instance methods of Promise:then,catch,finally;
  • Promise has four static methods:resolve,reject,all,race;

Iii. Promise Instance API (Prototype method)

There are four instance methods of Promise, namely, then, Catch and finally.

1, Promise. Prototype. Then ()

Function is introduced

  • Each Promise instance has a THEN method;
  • Promise’s handling of the results of an asynchronous operation:
    • The state is updated to success by calling resolve to enter then success callback processing.
    • Reject is called to update the state to a failed state, and then failure callback processing is entered.
  • Ondepressing and onRejected are the two parameters of the THEN method:
    • The first parameter: ondepressing successful callback: will be called when the successful state is fulfilled;
    • The onRejected callback is called when the failed state is rejected.

Code sample

// Promise has three states: success state, failure state, and wait state (default)
// call resolve, update state to successful, then successful callback;
Reject (reject); reject (reject); reject (reject)
// The state of each promise instance can be changed only once;
let promise = new Promise((resolve, reject) = >{
  console.log('promise')
  resolve("Success");     // Enter then successfully
  // reject(" reject "); // Enter then failed processing
  // throw new Error(" Error "); // Enter then failed processing
})

promise.then((value) = >{
  console.log('success', value) // Ondepressing: this will be called when the successful state is fulfilled
},() = >{
  console.log('err')     // onRejected: this parameter is invoked in the failed state
})

console.log('ok')

// Execution result:The promise will be fulfilled asynchronously, and then the onFulfilled function will be fulfilled. This is a big pityCopy the code
  • From the console output, you can see that the executor is executed immediately after the Promise instance is created, but the then method is executed asynchronously.

Remark:

  • A call to resolve enters a success processing;
  • Call reject or an exception will enter failure processing;
  • If neither resolve nor reject is called in the Promise, the Promise is in wait state by default. A success or failure callback is not entered, that is, the THEN method is not entered;

Enter the condition

The then() callback is entered when both the Promise body task and all the previous callback tasks in the chain call succeed (that is, through the resolve annotated state);

2, I Promise. The prototype. The catch ()

Function is introduced

The promise.prototype.catch () method is an alias of.then(null, Rejection) or.then(undefined, rejection) to specify a callback when an error occurs;

Code sample

Enter the condition

The catch() callback is entered when an exception occurs in the Promise body task and the previous chained call and is not caught (i.e., it is marked reject or a JS native error occurs and is not processed).

3, Promise. Prototype. Finally ()

Function is introduced

Code sample

Enter the condition

Regardless of success or failure in the chain call, the finally method will eventually be executed unless.finally handling is not added;

Promise static API (Class methods)

Promise has four static methods, namely, resolve, Reject, All and race.

1, Promise. Resolve ()

Function is introduced

  • Promise.resolve() : Creates and returns a successful Promise instance;
  • Often used to build microtasks; Build macro tasks are commonly usedsetTimeout);

Code sample

The following example is fine, but is a redundant Promise wrapper:

// Redundant Promise encapsulation
function getData() {
  return new Promise((resolve) = > {
    const a = 1;
    const b = 2;
    constc = a + b; resolve(c); })}Copy the code

Resolve can be used directly to quickly create a Promise object with a successful state and build it into a microtask:

function getData() {
  const a = 1;
  const b = 2;
  const c = a + b;
  return Promise.resolve(c); // Create a success state PROMISE instance and place it in the microtask queue
}
Copy the code

2, I Promise. Reject ()

Function is introduced

  • Promise.reject() : Creates and returns a failed Promise instance;

Code sample

3, Promise. All ()

Function is introduced

Code sample

4, Promise. Race ()

Function is introduced

Code sample


Five, the end

This paper mainly introduces the relevant functions and features of Promise through examples.

In the next chapter, we introduce the Promise A+ specification, which will implement A Promise from 0 to 1.


Maintain a log

  • 20211025
    • Reorganize the outline of the article, sort out the catalogue, expand the relevant content;
    • Update the abstract;
  • 20211103
    • Correct typos;