There is a problem with the source code of promise. Google didn't come here to ask for help.

problem description

read a piece of promise source code

I don"t understand this paragraph very much

js

final value received when function resolve (value) {/ / value is successful

    if(value instanceof Promise) {
        return value.then(resolve, reject);
    }
 }
 
 

what result do you expect? What is the error message actually seen?

The resolvePromise function in

promise has not passed

.

if (x instanceof Promise)

else if (x! = null & & ((typeof x = "object") | | (typeof x =" function"))

Why do you want to judge whether value is promise when it comes to resolve

Apr.08,2022

it can be understood that receiving a resolve indicates that the promise at this stage has returned successfully, but doesn't care what the return value is.

so the value instanceof Promise layer of judgment is needed. If promise is returned, the then operation is performed, and then the resolve method is entered and the loop is executed until the end of the chained method.


consider the following code:

let promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise1')
  }, 5000)
})

let promise2 = new Promise((resolve, reject) => {
  resolve(promise1)
}).then(result => {
  console.log(result) // 5spromise1
})

when you resolve a promise , there are two results:

  1. treat the promise object as the result of the promise resolve ;
  2. treat the result of the promise object resolve as the result of the promise resolve ;

if you want result 1 , if (x instanceof Promise) this code is not needed, but the specification of promise should be result 2 , so most implementations will have this if (x instanceof Promise) judgment.
when the above code is actually run in the browser, the string promise1 is log after about 5 seconds. If it is result 1, it should be a relatively fast log to produce a promise object . Another example is the following:

let promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise1')
  }, 5000)
})

let promise2 = new Promise((resolve, reject) => {
  resolve('promise2')
}).then(() => {
  return promise1
}).then(result => {
  console.log(result) // 5spromise1
})
Menu