javascript - 如何在节点中调用调用序列-> Express ^4.14
问题描述
我有要求在 API 返回的响应中搜索给定的“密钥”。我必须使用不同的输入多次调用相同的 API。从 API 获得响应后,我需要在 API 响应中搜索 KEY。如果 KEY 不存在,则使用不同的输入再次调用相同的 API 并搜索 ...继续。
基本上,直到我完成一次在 API 响应中搜索 KEY 的迭代,执行应该等待。怎样才能做到这一点?请建议。
我已经尝试过以下方法和执行,而不是等到它在 API 响应中搜索键。
for (i=0;i< departments.length;i++)
{
getInformation(departments[i]).
then((response) => {
//verify whether given key present in response
})
.catch((err)) => {
//log error
});
}// end of for loop
}
注意:我想继续使用下一个键进行搜索操作,即使它们是 API 调用之一中的任何异常。
谢谢
解决方案
你必须使用递归
let departments = [xxx]
let myResult = []
const search = (pool, resolve, reject) => {
if (pool.length === 0) {
return resolve()
}
let [department, ...rest] = pool
getInformation(department)
.then(data => {
myResult.push('something')
})
.catch(e => {})
.finally(() => {
search(rest, resolve, reject)
})
}
const searchInDeps = new Promise((resolve, reject) => {
search(departments, resolve, reject)
})
searchInDeps
.then(() => {
// do something with myResult
})
.catch(e => {})
需要循环的另一种方式是,您可以运行每个 Promise,并等待所有结果。
let searches = []
for (i=0;i< departments.length;i++) {
searches.push(new Promise((resolve, reject) => {
getInformation(departments[i])
.then(data => {
resolve('something')
})
.catch(e => resolve('something'))
})
}
Promise.all(searches)
.then(results => {
// array of results
})
.catch(error => {})
推荐阅读
- javascript - Axios 发布和上传图像在 IOS/IPhone (HTTP 400) 上的 Safari 不起作用
- r - 如何在蒙特卡洛模拟中添加均值和标准差线?
- protractor - Protractor 5.4.2 和 Webdriver 12.1.6 以及 chromedrivers 不支持 chrome 76
- amazon-web-services - 嵌套数组(属性)的分页
- javascript - 使用 GET 提交一些数据,一些使用 POST 提交到同一页面
- powershell - 使用 Authenticationn/Access Token 访问 TeamCity 会出现错误 401 Unauthorized
- intellij-idea - Intellij Idea 中“服务器问题”检查严重性的含义
- typescript - 如何在 TypeScript 中将字符串细化为“字符串枚举”?
- c# - 通过 api 控制器向用户发送主动消息
- css - 在悬停声明中引用父元素而不给它特定的名称