首页 > 解决方案 > 如何在Javascript中重新排列嵌套的promise

问题描述

我是 javascript 承诺方法的新手。我有一个 html 页面,我需要从中使用 javascript 进行几个 api 调用。api 调用应该一个接一个地进行(仅当一个 api 调用成功时才转到下一个 api 调用等)。

我尝试在链中使用 javascript 承诺(下面的伪代码),它正在工作。

function getalldata()
{
    //few lines of code before 1st api call
    APImethod1.then{
    //few lines of code after 1st api call
    }
    .then{
            /few lines of code before 2nd api call
            APImethod1.then{
            //few lines of code after 2nd api call
            }
        }
        .then{
                /few lines of code before 3rd api call
                APImethod1.then{
                //few lines of code after 3rd api call
                }
            }
            .then{
                    /few lines of code before 4th api call
                    APImethod1.then{
                    //few lines of code after 4th api call
                    }
                //and so on         
                }   
}

但是嵌套代码看起来很乱,因为我必须进行几个 api 调用并且代码块更多。所以我想将每个 api 调用保持在一个单独的承诺中,最后按照我想要的顺序调用承诺。如下所示。

 function callAPImethods() {
            var promise1 = new Promise(function (Resolve, Reject) {
                console.log("promise1")
                Resolve("test1success");
            });
            var promise2 = new Promise(function (Resolve, Reject) {
                console.log("promise2")
                Resolve("test2success");
            });
            var promise3 = new Promise(function (Resolve, Reject) {
                console.log("promise3")
                Resolve("test3success");
            });

            console.log("start");
            promise1.then(
                function (value) {
                    promise2.then(function (value) {
                        promise3.then(function (value) {
                            console.log("end");
                        })
                    })
                })
        }

上面的代码似乎在底部调用之前先执行了 promise 块。控制台输出是 promise1 promise2 promise3 start

我希望仅在函数末尾调用时才执行承诺中的代码块。基本上我想要的控制台输出如下。提前致谢。开始承诺 1 承诺 2 承诺 3 结束

标签: javascript

解决方案


new Promise(your_executor_function)your_executor_function 立即致电。

这就是 promise 的工作方式。

在 Promise 上调用该then()方法决定了当 Promise 完成时会发生什么。

它不会触发your_executor_function(在您创建承诺时会触发)。


如果您想安排一些复杂的代码稍后运行:将它(即整个new Promise(...)代码)放在一个函数中,然后在需要时调用该函数。


您可能还想查看/语法asyncawait它可以节省一系列嵌套then调用。


推荐阅读