繁体   English   中英

nodejs - 多个异步http请求

[英]nodejs - multiple async http requests

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

考虑到nodejs是异步的并且基于回调,我想知道实现这个目标的最佳方法是什么才能拥有“干净的代码”并且不会过多地搞乱代码。

感谢任何提示/指导,马克

也许看看Async库。 有很多内置功能似乎可以实现您所需要的功能。 一些有用的直接击球可能是“async.waterfall”和“async.map”。

async.waterfall

async.map

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

Native Promise Docs - MDN

对于您的特定问题,imo,npm模块请求 - 承诺提供了一些很好的解决方案。 它本质上是请求模块的“Promisified”版本:

它将允许您进行GET / POST / PUT / DELETE并使用a跟进每个请求。 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()将被传递给函数。

请求承诺

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM