如何在expressjs nodejs中嵌套REST GET请求

假设我的路由文件具有以下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 }); } }); } 

该端点使用RESTful Web服务,结果如下所示:

 { users : [{ id : 12345 },{ id : 23456 },{ id : 34567 }]} 

现在我想知道如何/在哪里做第二。 REST GET请求( /userinfo从第一个请求的结果中检索用户的额外信息(基于user.id并更新第一个。 结果与第二。

问候

使用只支持callback的httpClient ,最好的办法是为每个步骤创build一个函数,避免深度嵌套块:

 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) } 

async库可以帮助你做到这一点。

我不build议这两种方法。 相反,使用支持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))