This is the third day of my participation in the August More Text Challenge

The meaning of the Promise

  • PromiseIs a solution to asynchronous programming, mainly to solve the traditional callback function callback hell problem.
  • es6Writing Promise into the language standard, unifying its use,Native provides Promise objects.

The characteristics of

  • The state of the Promise object is unaffected. Three states:
    • pending(In progress)
    • fulfilled(has been successful
    • rejected(Failed)
  • Once the state changes, it will never change again, and you can get this result at any time.
    • States can only be created frompeddingintofulfilled, or frompeddingintorejected

disadvantages

  • Once theThe new PromiseIt would beExecuted immediatelyCan’t cancel midway. (That is, new Promise() will be implemented immediately, involving the EventLoop interview questions.)
  • If the callback function is not set, errors thrown inside a Promise are not reflected outside.
  • When in pedding state, it is impossible to know the current progress stage (just started or about to be completed).

Basic usage

  • The Promise object is a constructor that generates a Promise instance.
  • Promise constructorTake a function as an argument.
  • The function that takes arguments takes two argumentsresolvereject.
  • resolverejectIt’s also two functions that the javaScript engine doesn’t have to deploy itself.

Knowing these characteristics of the Prmise constructor, you can try to instantiate a promise

const promise = new Promise((resolve, reject) = > {
    if(/* Asynchronous operation succeeded */) {
        resolve(value)
    } else {
        reject(error)
    }
})
Copy the code
  • The resolve function:, the state of the Promise objectChanged from Pedding to ResolvedIn theCalled when the asynchronous operation succeedsAnd pass the result of the asynchronous operation as a parameter.
  • Reject function: Changes the state of the Promise object from PEDding to Rejected in an asynchronous operationWhen the failureCall, and pass the error reported by the asynchronous operation as an argument.
  • Once a Promise instance is generated, you can use the THEN method on its prototype chain to specify the callback functions for the Resolved state and the Rejected state, respectively.
  • The THEN method takes two parameters, a successful callback and a failed callback. Both successful and failed callback functions accept the value from the Promise object as an argument. (This is the value that resolve and Reject throw as arguments when we use new Promise.)

promise.then((value) = > {
    // This method is a successful callback
    console.log(value)
}, (error) = > {
    // This method is a failed callback
    console.log(error)
})
Copy the code

Pay attention to the point

  • If a promise’s resolve accepts another promise as an argument, an asynchronous operation returns another asynchronous operation as a result. As follows:
const p1 = new Promise(function (resolve, reject) {
  setTimeout(() = > reject(new Error('fail')), 3000)})const p2 = new Promise(function (resolve, reject) {
  setTimeout(() = > resolve(p1), 1000)
})

p2
  .then(result= > console.log(result))
  .catch(error= > console.log(error))
// Error: fail
Copy the code

P1 is passed to P2 as a parameter, and the state of P1 determines the state of P2. If P1’s state is pending, p2’s callback waits for p1’s state to change. If P1 is in resolved or Rejected, the P2 callback will be executed immediately.

In the code above, p2 will execute resolve after 1 second to change the state to resolved. However, p2’s callback function will accept P1 as its parameter. In this case, P2’s state will not be determined by p1. P1 is still in pedding state at this moment, so P2 needs to wait for the status change of P1. After 2 seconds, P1 calls reject and its status changes to Rejected. At this time, P2’s callback function is executed immediately and its status changes to rejectd.

  • Resolve or reject does not terminate the execution of the Promise argument function. That is, code after resolve() will still be executed and output before resolve().
  • The Resolved Promise is executed at the end of this event cycle.
  • The following is usually recommended:
new Promise((resolve, reject) = > {
  return resolve(1);
  // The following statement will not be executed
  console.log(2);
})
Copy the code

Promise.prototype.then()

  • The then method is defined on the prototype object Promise.Prototype.
  • The then method adds a callback to the Promise instance when the state changes.
  • The then method accepts two optional arguments:
    1. Successful callback function
    2. Failed callback function
  • Then methodA new Promise instance is returned.So you can make chain calls.

Promise.prototype.catch()

  • The same catch is defined on the prototype object Promise.prototype.
  • Promise.prototype.catch() is an alias for.then(null, Rejection) or.then(undefined, Rejection) to specify a callback when an error occurs.
  • then()The callback function specified by the method is also called if an error is thrown during executioncatch()Method capture.
  • Errors from the Promise object are bubbling and are passed backwards until they are caught. That is, an error is always caught by the next catch statement.
  • Without a callback that uses the catch() method to specify error handling, the error thrown by the Promise object is not passed to the outer code, nor is there any response.
  • Errors within a Promise do not affect the code outside of the Promise, which is commonly known as "Promise eats errors."Look at the following example:
const someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    // The next line is an error because x is not declared
    resolve(x + 2);
  });
};

someAsyncThing().then(function() {
  console.log('everything is great');
});

setTimeout(() = > { console.log(123)},2000);
// Uncaught (in promise) ReferenceError: x is not defined
/ / 123
Copy the code

In the above code, the subsequent code will still output 123 after the internal error of the promise, so it can be seen that the internal error of the promise will not affect the external code of the promise.

Promise.prototype.finally()

  • Finally is also defined on the prototype object Promise.prototype.
  • The finally() method is used to specify actions that will be performed regardless of the final state of the Promise object. That is, finally methods are always executed.
  • finallyMethod does not accept any arguments.
  • finallyThe actions in the method should be state independent and not depend on the result of the Promise’s execution.
  • finallyEssentially,thenMethod special case.

Simple implementation finally

Promise.prototype.finally = function (callback) {
    let P = this.constructor;
    return this.then(
        value= > P.resolve(callback()).then(() = > value),
        reason= > P.resolve(callback()).then(() = > {throw reason})
    )
}
Copy the code

Promise.all()

  • Promise.all()Method is used to wrap multiple Promise instances into a new Promise instance.
const p = Promise.all([p1, p2, p3]);
Copy the code
  • Promise.all()Accepts an array as an argument. It may not be an array, but it must have an Iterator interface and each member returned is a Promise instance.
  • onlyp1,p2,p3The state of theta becomesfulfilled.pWill becomefulfilledAt this time,p1,p2,p3To form an array of return values passed topThe callback function of.
  • As long asp1,p2,p3One of them wasrejected.pThe state of theta becomes thetarejectedAt this time, the first to berejectIs passed topThe callback function of.
  • If the Promise instance, as an argument, defines itselfcatchMethod, then once it isrejected, does not triggerPromise.all()thecatchMethods.

Promise.race()

  • Promise.race()Again, you wrap multiple Promise instances into a new Promise instance.
const p = Promise.race([p1, p2, p3]);
Copy the code
  • As long asp1,p2,p3One of them was the first to change state,pThe state of the changes. The return value of the first changed Promise instance is passed topThe callback function of.
  • Promise.race()Method parameters andPromise.all()Same method, if it is not a Promise instance, it will be called firstPromise.resolve()Method, turn the parameters into a Promise instance, and proceed further.

Promise.allSettled()

  • Promise.allSettled()Method takes a set of Promise instances as parameters and wraps them into a new Promise instance. Wait until all of these parameter instances return results, either wayfulfilledorrejected, the wrapping instance will end.
  • The method returns a new Promise instance, and once finished, the state is alwaysfulfilledWill not becomerejected.
  • State intofulfilledAfter that, Promise’s listener receives an array of parameters, one for each memberPromise.allSettled()Promise instance of.

Promise.any()

  • Promise.any()The method takes a set of Promise instances as parameters and returns them wrapped as a new Promise instance.
  • As long as one of the parameter instances becomesfulfilledState, the wrapper instance will becomefulfilledState; If all parameter instances becomerejectedState, the wrapper instance will becomerejectedState.
  • Promise.any()The Error thrown is not a generic Error object, but an AggregateError instance. It’s like an array, one for each memberrejectedThe error thrown by the operation.

Promise.resolve()

  • Promise.resolve() is used to turn an existing object into a Promise object.
Promise.resolve('foo')
/ / equivalent to the
new Promise(resolve= > resolve('foo'))
Copy the code
  • Promise.resolve()The parameters of the method can be divided into four cases:
    1. The argument is an instance of Promise: If the argument is an instance of Promise,Promise.resolveThe instance is returned intact, with no modifications.
    2. The argument is a Thnable object: (thenableObject refers to havingthenMethod object),Promise.resolve()Method converts this object to a Promise object and executes immediatelythenableThe object’sthen()Methods.
    3. Parameters are not objects with then() methods, or not objects at all: If the parameter is a primitive value, or a parameter that does not havethen()Method, thenPromise.resolve()Method returns a new Promise object in the state ofresolved.
    4. No arguments:Promise.resolve()The method allows you to call with no arguments and return oneresolvedState Promise object.

Promise.reject()

  • Promise.reject(reason)The method also returns a new Promise instance with a state ofrejected.
  • Promise.reject()The parameters of the method are left as they arerejectBecomes the parameter of the subsequent method.

This article is from: GETTING Started with ES6