我试图简化我的代码,本质上我有以下几点:



    function thirdPartyAPIMethod() { // Dummy method returning promise
       return Promise.resolve();
    }

    function func1() {
        console.log("func1 start");
        return thirdPartyAPIMethod().then(() => {
            console.log("func1 end");
            // ...
            resolve();
        });
    }

    function func2() {
        console.log("func2 start");
        // ...
        console.log("func2 end");
    }

    func1().then(func2());





我要运行func1,完成后再运行func2。所以我期望输出是这样的:

func1 start
func1 end
func2 start
func2 end


但是,它会打印以下内容:

func1 start
func2 start
func2 end
func1 end


有人可以帮我做到这一点吗?

最佳答案

修改func1以在resolve承诺已解决后调用thirdPartyAPIMethod's



function thirdPartyAPIMethod() //dummy method returning promise
{
   return Promise.resolve();
}


function func1() {
    return new Promise((resolve, reject) => {
        console.log("func1 start");
        thirdPartyAPIMethod().then( () => {
           console.log("func1 end");
           resolve(); //invoke resolve here so that func1() is chained with func2
        });
    });
}

function func2() {
    console.log("func2 start");
    console.log("func2 end");
}

func1().then( () => func2()); // then has function callback handler instead of return value of func2

关于javascript - Javascript Nested Promise无法按预期顺序运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49690914/

10-11 06:11
查看更多