1) Basic features of promises

  • This is a big pity. Promise has three states: Pending, fulfilled and rejected.
  • The Promise object takes as an argument a callback that takes two arguments, resolve on success and Reject on failure. In addition to the normal value, the resolve parameter may also be an instance of a Promise object. The reject argument is usually an instance of an Error object.
  • The then method returns a new Promise instance and accepts two parameters onResolved and onRejected(the callback of the fulfilled state, which is optional).
  • The catch method returns a new Promise instance.
  • The finally method executes regardless of the Promise state, and its callback takes no arguments.
  • The promise.all () method wraps multiple Promise instances into a new Promise instance that takes an array of Promise objects as arguments. (The promise.all () method may not take an array, The promise.all () method returns a catch method for the new Promise instance, but it must have an Iterator interface and each member returned is an instance of a Promise. If an instance in the argument itself calls a catch method, the catch method of the new instance returned by the promise.all () method will not be triggered.
  • The parameters of the promise.race () method are the same as those of the promise.all () method. If one of the instances in the parameter changes state first, the state of that instance is passed to the promise.race () method. The return value is used as the return value of the Promise instance produced by the promise.race () method.
  • Promise.resolve() converts an existing object to a Promise object. If this method takes a Promise object, promise.resolve () does nothing; If the argument is a Thenable object (that is, with a then method), promise.resolve() turns that object into a Promise object and executes the then method immediately; The Promise. Resolve () method returns a new Promise object, which is fulfilled, if the parameter is a primitive value, or an object that does not have a then method. Its arguments will be used as arguments to the onResolved callback in the THEN method; If the promise.resolve method takes no parameters, a fulfilled Promise object will be returned directly. Note that, with no arguments, the returned Promise object is executed at the end of this event loop, not at the beginning of the next.
  • Promise.reject() also returns a new Promise object in the rejected state, and any arguments passed will be accepted as reject() arguments.

2) Promise

  1. Unified Asynchronous API
    • One important benefit of Promise is that it will increasingly be used as an asynchronous API for browsers, unifying the various apis and incompatible patterns and approaches that exist today.
  2. Promises versus events
    • Promises are better suited to handling one-time results than events, and it’s okay to register callbacks before or after the results are calculated to get the correct value. This advantage of promises is natural, but you can’t use promises to handle events that are triggered more than once. Chained processing is another advantage of promises, but events cannot be chained in this way.
  3. Promise vs. callback
    • The problem of callback hell is solved by expressing asynchronous operations as a flow of synchronous operations.
  4. Promises have the added benefit of including better error handling (including exception handling) and being easier to write (because you can reuse synchronous tools like array.prototype.map ()).

3) Disadvantages

  • There is no way to cancel a Promise, which is executed as soon as it is created and cannot be cancelled halfway through.
  • If the callback function is not set, errors thrown from within a Promise are not reflected externally.
  • When you are in a Pending state, you have no way of knowing what stage of progress you are currently in (just started or about to complete).
  • By the time the Promise actually performs the callback, the part that defines the Promise is actually gone, so the Promise’s error stack context is not very friendly.

4) Simple code implementation

The simplest Promise implementation has seven primary properties, state, Value, Reason, resolve, Reject, and then.

class Promise {
    constructor(executor) {
        this.state = 'pending'
        this.value = undefined
        this.reason = undefined
        let resolve = value= > {
            if(this.state === 'pending') {
                this.state = 'fulfilled'
                this.value = value
            }
        }
        let reject = reason= > {
            if(this.state === 'pending') {
                this.state = 'rejected'
                this.reason = reason
            }
        }
        try {
            // Execute the function immediately
            executor(resolve, reject)
        } catch (err) {
            reject(err)
        }
    }
    then(onFulfilled, onRejected) {
        if(this.state === 'fulfilled') {
            onFulfilled(this.value)
        } else if(this.state === 'rejected') {
            onRejected(this.reason)
        }
        
    }
}
Copy the code

5) The interview version

function myPromise(constructor) {
    let self = this
    self.status = 'pending' // Define the initial state before the state changes
    self.value = undefined // Determine the resolved state
    self.reason = undefined // Define the state of the rejected state
    
    function resolve(value) {
        // Two === 'pending' guarantees that state changes are irreversible
        if(self.status === 'pending') {
            self.value = value
            self.status = 'resolved'}}function reject(reason) {
        // Two === 'pending' guarantees that state changes are irreversible
        if(self.status === 'pending') {
            self.value = reason
            self.status = 'rejected'}}// Catch a construction exception
    try {
        constructor(resolve, reject)}catch(e) {
        reject(e)
    }
}
myPromise.prototype.then = function(onFulfilled, onRejected) {
    let self = this
    switch(self.status) {
        case 'resolved':
            onFulfilled(self.value)
            break
        case 'rejected':
            onRejected(self.reason)
            break}}/ / test
var p = new myPromise(function(resolve) { resolve(1) })
p.then(function(res) { console.log(res) })
/ / output 1
Copy the code