javascript - 需要使用node js在循环中调用两个API
问题描述
我有一个 ssn 号码数组,我有两个 api 列表,我需要在其中将 ssn 号码作为请求 json 传递,所以我需要在 ssn 循环内调用两个 api,所以我在调用两个 api 期间将 ssn 传递给 json 请求,但代码不起作用正确地同时调用两个api,我需要一个一个调用两个api。
API详细信息和代码如下
我的代码:
let ssn = [460458524, 637625452, 453311896, 635285187, 455791630, 642348377, 463590491, 450730278, 641201851, 379965491];
async function getCRCDetails() {
ssn.forEach(function (item) {
if(item){
let CBCOptions = {
'method': 'POST',
'url': 'https://loanboard.houstondirectauto.com/api/Report',
'headers': {
'Content-Type': 'application/json',
'Cookie': 'ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p'
},
body: JSON.stringify({
"token": loantoken,
"action": "CBCReport",
"variables": {
ssn: item
}
})
}
request(CBCOptions, function (error, response) {
console.log(item);
console.log("CBCOPtion ", CBCOptions);
if (error) throw new Error(error);
result = (JSON.parse(response.body));
console.log("Result =", result);
CRCReport.push(result);
})
let EmployerInfoOptions = {
'method': 'POST',
'url': 'https://loanboard.houstondirectauto.com/api/Report',
'headers': {
'Content-Type': 'application/json',
'Cookie': 'ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p'
},
body: JSON.stringify({
"token": loantoken,
"action": "getEmployerInfo",
"variables": {
ssn: item
}
})
}
request(EmployerInfoOptions, function (error, response) {
console.log(response.body);
})
}
这里我需要一一调用API请求。请大家指导我。
解决方案
在 Node 中,您使用的请求方法是异步的。这意味着运行代码的运行程序(服务器)不会等待请求完成,而是继续执行下一行。
你可以做的一件事是,
request.post(params).on("response", function(response) {
//....Do stuff with your data you recieve
// Make the next call here
request.post(params).on("response"), function() {
// Here you will have the second call's results
}
})
这可确保两个 API 调用都按顺序发生,并且仅在第一个调用完成后发生。
笔记:
您使用的request
库已于 2020 年弃用。请参阅https://github.com/request/request因此,我建议您使用其他库,例如node 附带的标准https
或库,或者您可以使用.http
axios
推荐阅读
- azure-ad-b2c - Azure AD B2C 中的 strongAuthenticationEmail 和 strongAuthenticationPhoneNumber 属性
- laravel - 正确地将图像上传到数据库。Laravel vue.js
- c++ - 如何从文件读取信息到矩阵?
- java - Oauth ResourceServer 中的自定义 UserAuthenticationConverter
- python - 如何在python中对视频进行阈值处理?
- laravel - 获取输入值并将其传递给同一刀片文件 Laravel 5.7 中的路由
- scala - Scala 编译器是否有可能理解重写的抽象类型
- excel - 针对具有字符串数据的列(Excel、VBA、宏)循环和扫描例如 200 个字符串的列表
- android - 构建 Ionic React android 应用程序后卡在白屏
- sitefinity - 如何将我的代码集成到 sitefinity 项目中