javascript - JS:复杂的承诺链
问题描述
在尝试使用 Promises 和回调链接复杂的函数调用时,我遇到了一个小问题。
我有一个主函数,它调用子例程。在这些例程中进行 API 调用。
例如:
function handle(){
new Promise(function(resolve, reject){
let result = doAPICall1()
if (result === true) resolve(true);
reject(JSON.stringify(result))
}).then(function(){
let result = doAPICall2()
if (result === true) return true
throw new Error(JSON.stringify(result))
}).catch(error){
console.error(JSON.stringify(error))
}
}
function doAPICall1(){
axios.get('...').then(function(){
return true
}).catch(function(error){
return error
})
}
function doAPICall2(){
axios.get('...').then(function(){
return true
}).catch(function(error){
return error
})
}
但是当我执行这个例子时,doAPICall2 将被执行,而 doAPICall1 仍在运行。
它仅在进行长时间运行的调用时发生。
有人可以给我一个提示吗?谢谢!
解决方案
别担心,花点时间更好地理解 Promises。在下面的示例代码中,doAPICall
函数返回一个 Promise,它解析为一个值,而不是值本身。
function handle() {
doAPICall().then(result => {
//do something with the result
}).catch(error => {
//catch failed API call
console.error(error)
})
}
doAPICall() {
// this returns a Promise
return axios.get(...)
}
推荐阅读
- python - Selenium 无法获取页面的所有元素
- r - Cut elements from the beginning and end of an R vector
- python - IS there a CSV Quotechar function as in Python suitable for Bulk Insert into MS SQL Server?
- reactjs - 更新反应表单输入字段中的值
- php - 无法使用学说更新我的 Symfony 应用程序依赖项
- matlab - 从字母表中生成具有特定概率的随机字符串(randsrc 问题)
- python - How to split a pandas string to extract middle names?
- python - clip the text with a circular region
- android - 当内部活动开始以获得结果时处理主页按钮按下
- cudd - CUDD 使用非门