Let’s first sort out some basic concepts:

What is Promise?

Promises are a solution to asynchronous programming: syntactically, promises are an object that gets messages for asynchronous operations; In its original sense, it is a promise that will give you results over time.

What problems can Promise solve?

  • The callback hellCode is difficult to maintain, and often the output of the first function is the input of the second function

    As more and more asynchronous scenarios occur, the code grows horizontally (wider), the level of dependencies increases, and it becomes nested all the time, leading to callback hell.PromiseIt actually makes asynchronous calls more chained, enabling asynchronous operations to be queued and executed in the desired order, returning the desired result.
  • PromiseMultiple concurrent requests can be supported to retrieve data from concurrent requests
  • PromiseThis solves the problem of asynchrony, but it doesn’t by itself make promises asynchronous

An 🌰

// The callback functionconst callback=function() {    console.log('callback')
}
function callbackFn(fn){
 setTimeout(fn,3000) } callbackFn(callback) // Encapsulate the promiseconst promise =new Promise(function(resolve,reject){  console.log('success')  resolve() }) promise.then(  function() { setTimeout(callback,3000)  } ) Copy the code

Promise the pros and cons

advantages

  • Separating executing code from processing code makes asynchronous operation logic clearer.
  • Asynchronous operations can be expressed as a flow of synchronous operations, eliminating layers of nested callback functions (without stripping functions)returnSo there is no need for layers of transmissioncallbackTo call back to get data)
  • Object provides a unified interface that makes it easier to control asynchronous operations
  • Code style, easy to understand and maintain

disadvantages

  • Can’t cancelPromiseOnce created, it is executed immediately and cannot be cancelled midway
  • If you do not set the callback function,PromiseErrors thrown internally are not reflected externally
  • When inPendingState, you cannot know the current progress stage

Promise has three states

  • Initial state:pending(Waiting state)
  • Operation succeeded:fulfilled(Successful state)
  • Operation failure:rejected(Failed state)

Promise to use

Promise’s constructor accepts a function as an argument that takes two arguments:

  • resolve(): Callback function after the asynchronous operation is successfully executedPromiseThe state of the object changes from Incomplete to Succeeded (that is, frompendingintoresolved), is called when the asynchronous operation succeeds, and passes the result of the asynchronous operation as a parameter;
  • reject(): callback function for asynchronous operation failure, willPromiseThe state of the object changes from incomplete to Failed (that is, frompendingintorejected), is called when an asynchronous operation fails, and an error reported by the asynchronous operation is passed as an argument. In the implementationresolveIf an exception is thrown (the code went wrong), then no error is reportedjsI’m going to go into thiscatchMethods.
  • whenPromiseTrigger when the state changesthen()The response function in the. createPromiseAfter instance, it will execute immediately,PromiseOnce a state has changed, it cannot change again.
  • When there is a.then()There is a.then()As a result of.then()I’ll return the Promise instance, and I’ll wait for it.then()When we’re done, we’ll do the outside
let p = new Promise((resolve, reject) => {
// Do some asynchronous operations      setTimeout(function() {var num = Math.ceil(Math.random()*10); // Generate random numbers from 1 to 10            if(num<=5){
 resolve(num);  }  else{  reject('The numbers are too big');  }  }, 2000);  });  p.then((data) => {  console.log('resolved',data);  },(err) => {  console.log('rejected',err);  }  ); Copy the code

Promises/A+ Promises *

In the final analysis, Promises/A+ provides A complete explanation of how Promises are implemented and used. All questions about Promises can be answered here. Official address: promisesaplus.com

Because the official website is in English version, in order to facilitate reading and understanding, combined with Google Translation myself translated, the level is limited, welcome to correct any questions, grateful heart 💗💗

Text of the specification :(cited 🌰 supplement)

An open, implementable, interoperable standard of JavaScript promised by implementors for implementors.

A Promise represents the end result of an asynchronous operation. The primary way to interact with a promise is through its THEN method, which registers callbacks to receive the final value of the promise or the reason why the promise could not be fulfilled.

The specification details the behavior of the THEN method and provides an interoperable foundation on which all Promises/A + compatible Promise implementations can rely. Therefore, the specification should be considered very stable. Although Promises/A + organizations will sometimes revise this specification with minor backward compatible changes to address newly discovered extremes, we will only integrate large or backward compatible changes after careful consideration, discussion, and testing.

Promises/A + historically, Promises/A + clarifies the act clause of earlier Promises/A proposals, expanding it to cover actual acts and omits unspecified or problematic parts.

Finally, the core Promises/A + specification does not deal with how to make, keep, or reject Promises. Instead, it focuses on providing an interoperable then approach. Future work with these specifications may cover these topics.

The term
  • PromiseIs an object or function that complies with this specification and has then methods. (In a narrow sense, an object with a then method is a legitimate promise object.)
  • thenable(including,thenMethods are definitionsthenThe object or function of a method.
  • The value (value)Is anything legalJavaScriptValue (includingundefined.thenableorpromise).
  • ExceptionIs the value raised using the throw statement.
  • There is no reason for this.Is a value indicating the reason for rejecting a commitment.
requirements
The state of the promise

A promise must be in one of three states: pending, fulfilled, or rejected.

  • On hold:
    • Transitions may be made to completed or rejected states.
  • When completed:
    • No transition to any other state is permitted.
    • There must be a value that cannot be changed.
  • When rejected:
    • No transition to any other state is permitted.
    • There has to be a reason. It can’t be changed.

Here, “immutable” refers to an immutable identity (that is, ===), but does not imply deep immutability.

A then method

A promise must provide a THEN method to access its current or final value or cause.

Promise’s then method accepts two arguments:

promise.then(onFulfilled, onRejected)

  • The twoonFulfilledandonRejectedIs an optional argument:
    • ifonFulfilledIs not a function, it must be ignored.
    • ifonRejectedIs not a function, it must be ignored.
  • ifonFulfilledIs a function:
    • Must be inPromise is called after execution withPromise’s result as the first parameter.
    • inpromiseIt cannot be called until the execution is complete.
    • Cannot be called more than once.
  • ifonRejectedIs a function:
    • Must be inpromiseCalled after being rejected topromiseAs the first parameter.
    • inpromiseIt cannot be called until rejected.
    • Cannot be called more than once.
  • onFulfilledonRejectedNot called until the execution context stack contains only the platform code.
  • onFulfilledonRejectedMust be called as a normal function (that is, without this value) (non-instantiated call,thisIn non-strict mode it will point towindow).
  • Then may be called multiple times within the same promise.
    • whenpromiseWhen done, all correspondingonFulfilledIt must be executed in the order of its registrationthen.
    • whenpromiseWhen rejected, all correspondingonRejectedIt must be executed in the order of its registrationthen.

      promise2 = promise1.then(onFulfilled, onRejected);

  • thenMust be returnedpromise.
    • If I have oneonFulfilledonRejectedReturn a value x,promise2Enter theonFulfilledState. [1]
    • If any of themonFulfilledonRejectedRaises an exception E, thenpromise2E must be rejected and the rejection reason returned. [2]
    • ifonFulfilledIs not a function andpromise1If yes, thenpromise2This must be done using the same valuespromise1(Success). [3]
    • ifonRejectedInstead of a functionpromise1If rejected, thenpromise2It must be rejected for the same reason (failure). [4](each onepromiseIt just depends on the last onepromiseThe result of)
Here’s a look at the output from 🌰 :(decide which of the following cases will be output?)

(1)

const promise1 = new Promise(function (resolve, reject) {
    reject()
})
promise1
    .then(function () {
 return 123;  }, null)  .then(null, null)  .then(null, null)  .then(function () {  console.log('success promise')  }, function () {  console.log('error promise')  }) Copy the code

The output error promise

Promise1 returns null and is not a function (see [4]), keep descending onRejected until console.log(‘error promise’) (2)

const promise1 = new Promise(function (resolve, reject) {
   reject()
})
promise1
    .then(null,function () {
 return 456;  })  .then(null, null)  .then(null, null)  .then(function () {  console.log('success promise')  }, function () {  console.log('error promise')  }) Copy the code

Output success promise

Firstly, promise1 enters the onFulfilled state and the function returns a value of 456, which is referred to [1] above. Then promisE2 enters the onFulfilled state, which is referred to [4] above. Continue down until console.log(‘ Success promise’)

(3)

const promise1 = new Promise(function (resolve, reject) {
    resolve()
})
promise1
    .then(null, function () {
 return 456;  })  .then(null, null)  .then(null, null)  .then(function () {  throw Error('e')  }, null)  .then(function () {  console.log('success promise')  }, function () {  console.log('error promise')  }) Copy the code

The output error promise

[2], then enter the onFulfilled state and output console.log(‘success promise’). This is the big reward.

Promise resolution process

The Promise resolution process is an abstract operation that inputs a promise and a value, expressed as [[Resolve]](promise, x). If x is thenable, it behaves like a promise, trying to make the promise adopt the state of X. Otherwise, it will use value.

Promises/A + compatible THEN methods can interoperate with implementations of contracts as long as they expose Promises/A + compatible THEN methods. It also allows Promises/A + implementations to “assimilate” unqualified implementations with reasonable THEN methods. To run [[Resolve]](promise, x), perform the following steps:

  • ifpromisexIf the same object is referenced, theTypeErrorReject on the ground ofpromise.
  • ifxIs apromise, then its state is adopted:
    • ifxWaiting, thenpromiseYou have to wait untilxCompleted or rejected. [1]
    • ifxHas been completed,promiseIs completed with the same value. [2]
    • ifxHas been rejected,promiseAnd refused for the same reason. [3](The state of.then() depends on the state of the returned promise.)
Raise an 🌰 again
var promise1 =new Promise(function(resolve,reject){
    resolve('promise1')
})
var promise2 =new Promise(function(resolve,reject){
    resolve('promise2')
}) promise1.then(function(val){  return promise2 }).then(function(val){  console.log(val) }) Copy the code

Export promise2, refer to section [2] above

  • Otherwise, ifxIs an object or function (less common)
    • To perform firstx.then.
    • If you takex.thenThe result e of a thrown exception is rejected as reasonpromise.
    • ifthenIs a function, please usexAs athis, the first parameterresolvePromiseAnd the second parameterrejectPromiseCall, where:
      • ifresolvePromisecallyAs a value, run[[Resolve]](promise, y).
      • ifrejectPromisecallrAs a cause of refusalrReject as a causepromise.
      • If both callsresolvePromiserejectPromise, or if multiple calls are made to the same parameter, the first call takes precedence and any other calls are ignored.
      • If the callthenAn exception is throwne.
        • ifresolvePromiseorrejectPromiseAlready called, it is ignored.
        • Otherwise, in order toeReject as a causepromise.
    • ifthenIt’s not a function,promisecallxChanges to the completed state.
  • ifxNot an object or a function,promisecallxChanges to the completed state (common).
Another 🌰
var promise1 =new Promise(function(resolve,reject){
    resolve('promise1')
})
var promise2 =new Promise(function(resolve,reject){
    resolve('promise2')
}) promise1.then(function(val){  return val }).then(function(val){  console.log(val) }) Copy the code

Promise1, x is not an object or function

If a promise is resolved using thenable in a loop chain, [[Resolve]](promise, thenable) will cause recursion, and [[Resolve]](promise, thenable) will be called again, causing infinite recursion. It is recommended (but not required) to detect such recursion and reject promises on TypeError grounds.

Write a Promise by hand

Implement a promise of your own based on promiseA+. I’m not going to talk about it here, but I’ll recommend a few articles that I think are good for you

(In fact, I am writing my own is not perfect, and I will come back to fill the hole when I am satisfied)


Here are some common Promise methods

Promise.all

The slowest runner executes the callback. All takes an array of arguments, and the values in it eventually return a Promise object

The ability to execute asynchronous operations in parallel (in no order) and not execute callbacks until all asynchronous operations have been executed.

const promise = function (time) {
    return new Promise(function (resolve, reject) {
        return setTimeout(resolve(time), time);
    })
}
Promise.all([promise(1000), promise(3000)]).then(function (values) {  console.log('all', values.tostring ()) // All three are successful},function(e){ Console. log(e) // If there is a failure, it will fail}) Copy the code

Output all 10003000 after 3 seconds

Promise.race

The callback is based on the fastest runner.

const promise = function (time) {
    return new Promise(function (resolve, reject) {
        return setTimeout(resolve(time), time);
    })
}
Promise.race([promise(1000),promise(3000)]).then(function(value){  console.log('race',value) }) Copy the code

Output race 1000 after 1 second

You can use Race to set a timeout for an asynchronous request and perform the corresponding operation after the timeout

// Request an image resource    function requestImg() {        var p = new Promise((resolve, reject) => {
            var img = new Image();
            img.onload = function() { resolve(img);  }  img.src = 'Picture path';  });  return p;  } // The delay function is used to time the request function timeout() { var p = new Promise((resolve, reject) => {  setTimeout(() => {  reject('Image request timed out');  }, 5000);  });  return p;  }  Promise.race([requestImg(), timeout()]).then((data) =>{  console.log(data);  }).catch((err) => {  console.log(err);  }); Copy the code

Shoulders of giants (including handwritten Promise articles that are considered better)

  • Promise won’t…? Look here!! The most accessible Promise ever!!
  • 1. Write A Promise that Promises/A+ Promises from scratch
  • Promises/A+ 100 lines of code
  • Promise implementation principle (source code attached)
  • I Promise I will (10 questions)
  • Classic INTERVIEW Questions: The most detailed handwritten Promise tutorial ever

The last

Welcome to correct mistakes, see will be timely modification! Review the old and learn the new, I hope we can keep our hearts, never forget, there will be echoes.

The last

Sell an amway to their own group, welcome to love the front end of the little sisters to join us, learn together, common progress [interested please leave a message or private letter, but see will immediately reply] 💗💗💗💗


This article is formatted using MDNICE