Ensuring asyncronous '.then()' execution i

2019-09-02 18:23发布

问题:

I am using Typescript to write JS promises. I have a compound promise, i.e. promise which returns a promise I have:

test() {
    addElement("first")
        .then(
            function (val){
                addElement("second");
                console.log("second*);
            })
            .then(
            function (val){
                addElement("third");
                console.log("third*");
            });
}


export function addElement(elementText){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            resolve();
        }, Math.random() * 2000);
    })
    .then(console.log(elementText));
}

I would like these functions to print out, first, second*, second, third*, third. However, I get:

JS: first JS: second* JS: third* JS: third JS: second

How do I get the then to execute after the called promises' then has completed?

回答1:

You're not returning your promise in the then block. If you don't return the promise, then the then block will return undefined immediately, and nothing will wait for it. If you return a promise instead, then execution of the promise chain will pause until the promise you return has been satisfied.

test() {
    addElement("first")
        .then(
            function (val){
                console.log("second*");
                return addElement("second");
            })
            .then(
            function (val){
                console.log("third*");
                return addElement("third");
            });
}

Though I don't personally consider it a "rookie mistake", your description matches "Rookie Mistake #5" in Nolan Lawson's "We have a problem with promises"; read on for a more in-depth explanation.