nodejs - 多个异步http请求

时间:2016-04-19 20:43:22

标签: node.js

我刚刚开始使用nodejs,并希望创建一个简单的nodejs应用程序,它需要: - 首先请求/通过http获取一些初始数据, - 使用收到的json执行另一组请求(一些可以并行完成,一些需要先执行,一些接收数据将用于创建有效的URL)。

考虑到nodejs是异步的并且基于回调,我想知道实现这个目标的最佳方法是什么,以便清理代码'而不是太乱用代码。

感谢任何提示/指南,Mark

2 个答案:

答案 0 :(得分:1)

也许看看Async库。有很多内置功能似乎可以实现您所需要的功能。马上就有几个有用的可能是“async.waterfall”和“async.map”。

async.waterfall

async.map

答案 1 :(得分:0)

同意这是主观的,一般来说,走的路是承诺,有本土的承诺:

Native Promise Docs - MDN

对于您的特定问题,imo,npm模块请求承诺提供了一些很棒的解决方案。它本质上是一个“未经宣传的”#34;请求模块的版本:

它将允许您进行GET / POST / PUT / DELETE并使用。then()跟进每个请求,您可以继续执行更多调用:

- 这段代码首先从服务器获取一些内容,然后向该服务器发送其他内容。

function addUserToAccountName(url, accountName, username, password){
  var options = assignUrl(url); // assignUrl is not in this code
  request
  .get(options) //first get
  .auth(username, password)
  .then(function(res) {
    var id = parseId(res.data, accountName); //parse response
    return id;
  })
  .then(function(id) {
    var postOptions = Object.assign(defaultSettings, {url: url + id + '/users'})
    request.post(postOptions) // then make a post
      .auth(username, password)
      .then(function(response) {
        //console.log(response);
      })
      .catch(function(err) {
        console.log((err.response.body.message));
      })
  })
}

您可以继续使用.then()继续前一个.then()返回的任何内容。

Request-Promise