javascript - 如何在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 结束
解决方案
new Promise(your_executor_function)
your_executor_function
立即致电。
这就是 promise 的工作方式。
在 Promise 上调用该then()
方法决定了当 Promise 完成时会发生什么。
它不会触发your_executor_function
(在您创建承诺时会触发)。
如果您想安排一些复杂的代码稍后运行:将它(即整个new Promise(...)
代码)放在一个函数中,然后在需要时调用该函数。
您可能还想查看/语法,async
await
它可以节省一系列嵌套then
调用。
推荐阅读
- linux - 从字符串中grep一个字符/单词并计算Linux中出现的次数
- python - 无法在 Windows 10 上安装 pygame
- java - 跳转到上一个索引并继续循环
- c# - .NET MVC 5:在请求之间丢失 cookie
- javascript - 如何在 2 个不同的函数之间共享一个变量?
- ios - react-native run-ios 偶尔构建
- filter - 制表过滤器:取消组合过滤结果
- r - 尝试为几何分布查找 MLE 时出错
- haskell - Haskell 映射函数和 lambda 表达式
- javascript - 是否可以从 Node.js 中可用的路由自动生成 Swagger yaml?