[英]how to make nested REST GET requests in expressjs nodejs
Let's say my route file has the following REST endpoint: 假设我的路由文件具有以下REST端点:
app.get('/userlist', function (req, res) {
var httpClient = addon.httpClient(req);
httpClient.get('example.com/users',
function(error, response, body) {
if (!error && response.statusCode == 200) {
var users = JSON.parse(body);
users.forEach(function(user, index, arr)
{
//do the 2nd REST GET request here using user.id ???
}
res.render('userlist', {
content : users
});
}
});
}
The endpoint consumes an RESTful webservice and the result looks like this: 端点使用RESTful Web服务,结果如下所示:
{ users : [{ id : 12345 },{ id : 23456 },{ id : 34567 }]}
Now i would like to know how / where to do the 2nd. 现在我想知道如何/在哪里做第二次。 REST GET request ( /userinfo
) to retrieve extra information of the user (based on the user.id
from the result of the 1st. request) and update the 1st. REST GET请求( /userinfo
)检索用户的额外信息(基于第一个请求的结果中的user.id
)并更新第一个。 result with 2nd. 结果与第二。
Regards 问候
Using an httpClient
that only supports callbacks, your best bet is to create a function for each step and avoid deeply nested blocks: 使用仅支持回调的httpClient
,最好的选择是为每个步骤创建一个函数并避免深度嵌套的块:
function findFirstUser(callback) {
httpClient.get('example.com/users', (error, response, body) => {
var firstUserId = JSON.parse(body).users[0]
getUser(firstUserId, callback)
})
}
function getUser(id, callback) {
httpClient.get('example.com/users/' + id, callback)
}
The async
library can help you do this as well. async
库也可以帮助您做到这一点。
I do not recommend either approach. 我不建议使用任何一种方法。 Instead, use an httpClient
that supports Promises
, such as axios
: 而是使用支持Promises
的httpClient
,例如axios
:
httpClient.get('example.com/users')
.then(response => JSON.parse(response.body).users[0])
.then(userId => httpClient.get('example.com/users/' + userId))
.catch(error => console.error(error))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.