[英]NODE - wait until one api call has completed before triggering the next api call
我在一個路由添加用戶中發出了POST請求。 我創建了一個名為成功的數組。 請求返回響應后,我想觸發下一個API調用。
目前無法正常工作,因為我認為我也可能一次發送API請求。 我認為解決方案是等到第一個響應返回響應並完成后,再觸發下一個API調用。
這個假設正確嗎? 如果是這樣,有人可以建議如何實施嗎? 我試圖使用.on('end'....
請在下面查看我的代碼。
app.get('/add-users', function (req, res) {
var success = [];
var count = 0;
for(var i = 0; i < users.length; i++) {
var name = users[i].userId;
request({
url: url,
headers: {
'Authorization': 'Bearer ' + users[i].accessToken,
'Content-Type': 'application/json'
},
method: 'PUT',
json: true
}, function(err, resp, body){
if (!err && resp.statusCode === 200) {
success.push(name);
}
})
.on('end', function(){
console.log('this is the end');
count++;
if(count === users.length) {
res.json(success);
}
});
}
});
經典! 當我第一次處理節點時,我也遇到了這個問題。
Lemme首先復制代碼的某些部分來進行說明:
app.get('/add-users', function (req, res) {
// [...]
for(/* user in users */) {
request(/* [...] */)
.on('end', function(){
console.log('this is the end');
count++;
if(count === users.length) {
res.json(success);
}
});
}
});
與其他語言(例如Ruby)相比,節點執行非阻塞I / O。 這意味着它異步執行幾乎所有的I / O操作(例如發出HTTP請求)。 本質上,當您發起一個請求時,它不會等待響應。
在循環中,這意味着它將一個接一個地觸發所有請求,而無需等待它們的響應:
start loop
make request
make request
make request
end of loop
... a little later
handle response
handle response
handle response
我假設您想要的內容如下所示:
start loop
make request
handle response
make request
handle response
make request
handle response
end of loop
我發現繞過節點的非阻塞性質並執行順序請求的一個技巧是編寫一個如下的遞歸函數:
function getAllUsers(users) {
function getOneUser(users) {
let user = users.pop();
request(/* [...] */)
.on('end', function() {
console.log("done with ONE user");
if(users.length) { // do we still have users to make requests?
getOneUser(users); // recursion
} else {
console.log("done with ALL users");
res.json(success);
}
});
}
// make a copy of the original users Array because we're going to mutate it
getOneUser(Array.from(users));
}
上面的操作是向一個用戶發出一個請求,然后在響應到達時觸發另一個請求。
我希望這有幫助。
這是我通常將多個請求鏈接在一起的方式。 嘗試在循環內調用異步函數將無法以編寫代碼的方式工作。 相反,我建議您在初始請求的回調中調用下一個請求。
//set index
var index = 0;
function callAPI(user) {
//increment index
index++
request({request:object},function(err, res){
if (index <= users.length) {
callAPI(users[index])
}
});
}
//call function with 0 index
callApi(users[0])
另外,如果您在上面的代碼中console.log(name),您將自己看到問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.