DWQA QuestionsCategory: ProgramWhy does promise execute immediately when it is returned in promise? Please explain the principle. Thank you
MiniDeveloper asked 2 months ago

Here is the code

function retPromise(str) {
        return new Promise(resolve=>{
            resolve(str);
        })
    }
    
    Console.log (retpromise ("first")) // returns a promise object
    
    retPromise("x").then(str=>{
        return retPromise("first")
    }).then(str=>{
        Console. Log (STR) // returns "first"
    })
  1. Why is the return promise object in then resolved in the next then?
  2. Is the execution chain of the second then the second promise?
jokester replied 2 months ago

It’s a man-made rule. It’s hard to say what’s the principle of promise / A +

5 Answers
Orange red age answered 2 months ago

Promise’s idea is to treat all synchronous and asynchronous code as asynchronous code, and then method will return a newPromise(chain call), the first parameter of the then methodonfulfilledIt was beforePromiseThe object is invoked after the asynchronous call is completed.

then(onfulfilled, onrejected){
            //Each then method returns a new promise object to implement the chain call

            return new Promise((resolve, reject)=>{

                let success = (value)=>{
                    //Here, perform onfulfilled to determine whether it is a promise object and pass the returned result as a parameter to the reslove of the current promise
                    //If there is no return value, the original value will be returned by default. This step is not necessary
                    let result = onfulfilled(value) || value;
                    if (isThenable(result)){
                        result.then((value)=>{
                            resolve(value);
                        }, (value)=>{
                            reject(value);
                        });
                    }else {
                        resolve(result);
                    }
                }

                let error = (value)=>{
                    let result = onrejected(value) || value;
                    resolve(result);
                }
                
                //When the promise object of the then method is called onfulfilled, success is called to perform the above operations
                switch(this.status){
                    case PENDING:
                        this.onfulfilled = success;
                        this.onrejected = error;
                        break;
                    case FULFILLED:
                        success(this.value);
                        break;
                    case REJECTED:
                        error(this.reason);
                        break;
                }
                
            })
        }

It’s still involved herePromiseSome implementations inside the constructor just implemented a simple promise a few days ago. Here isPortal, hope to help you

Cecil0o0 answered 2 months ago

I’m not Daniel – I’ll describe my point of view.
The then chain call will take the return value of the previous then as the parameter. The internal implementation of promise’s then function is to process the return value with promise object. For example, the basic data type will directly return the promise object through promise.resolve (data). If it is a promise object, execute its resolve function to trigger the next then function.

XIZHENDAI answered 2 months ago

You can decompose the then execution chain into:

Var promise 1 = retpromise ('x '); // a promise returned by retpromise ('x') function
Var promise 2 = promise 1. Then (STR = > {// when the promise returned by retpromise ('x ') is executed successfully, a new promise, promise 2, is returned
 console.log(str);
 return retPromise("first");
})

promise2.then(str=>{
    console.log(str);
})

You can also use setTimeout to set function retpromise (STR) to delay return. It works better

   function retPromise(str) {
    return new Promise(resolve=>{
      //var str1;
       setTimeout(function(){ console.log(str); str = str + " success!"; resolve(str);}, 3000);
    })
}

cnwhy answered 2 months ago
  1. Why is the return promise object in then resolved in the next then?

First of all, understandpromiseOfthenMethod must return apromiseObject. This is the provision of promise / A + (otherwise, you can’t write code in chain). The promise pair will determine the state according to the execution of the function in then. If a promise pair is returned, the promise state will be synchronized tothenMethod on the promise pair returned by the
What you mean by “next then” is actually to return promise pairsthenMethod, since the promise pair returned earlier looks like resolve, it will naturally execute resolve;

  1. Is the execution chain of the second then the second promise?

This problem is easy to handle. You just need to take apart your code and have a look

var p1 = retPromise("x").then(str=>{
        console.log('mark');
        return retPromise("first")
    })
console.log('mark1');
p1.then(str=>{
    Console. Log (STR) // returns "first"
})
console.log('mar2');
/*
Result:
mark1
mar2
mark
first
*/

As a result, P1 is assigned and then method is executedreturn retPromise("first")This sentence has not been implemented yet, how could it be the same promise;
In fact, if promise executes then once, it will generate a new poise;

var p  = retPromise("x");
p.then() === p.then() //false
Big Sima answered 2 months ago

First of all, the then function returns a new promise, which is automatically created by calling the then function and has nothing to do with the return value of the parameter (callback function) of the then function.
Secondly, take the above code as an example:

retPromise("x").then(str=>{
    return retPromise("first")
}).then(str=>{
    Console. Log (STR) // returns "first"
})

The parameter of the resolve callback function in the second then function is the return value of the previous then function, but if the return value is promise, the resolve callback function parameter in the promise returned will be passed out, that is, the str value in the following code,

function retPromise(str) {
    return new Promise(resolve=>{
        resolve(str);
    })
}