简体   繁体   English

nodejs - 多个异步http请求

[英]nodejs - multiple async http requests

I have just started my journey with nodejs and would like to create a simple nodejs app that needs to: - first request/get some initial data from via http, - use received json to do another set of requests (some can be done in parallel, some needs to be executed first and data received will be used to create valid url). 我刚刚开始使用nodejs,并希望创建一个简单的nodejs应用程序,它需要: - 首先通过http请求/获取一些初始数据, - 使用收到的json执行另一组请求(有些可以并行完成) ,有些需要先执行,收到的数据将用于创建有效的URL。

Taking into account that nodejs is asynchronous and based on callbacks, I am wondering what is the best way to achieve this in order to have 'clean code' and not mess up with the code too much. 考虑到nodejs是异步的并且基于回调,我想知道实现这个目标的最佳方法是什么才能拥有“干净的代码”并且不会过多地搞乱代码。

Thanks for any hints / guidelines, Mark 感谢任何提示/指导,马克

Maybe check out the Async library. 也许看看Async库。 Has a lot of built in functionality that seems to accomplish what you're looking for. 有很多内置功能似乎可以实现您所需要的功能。 Couple of useful ones right off the bat might be "async.waterfall" and "async.map". 一些有用的直接击球可能是“async.waterfall”和“async.map”。

async.waterfall async.waterfall

async.map async.map

Agreed that this is subjective, in general the way to go is promises, there are native promises: 同意这是主观的,一般来说,走的路是承诺,有本地承诺:

Native Promise Docs - MDN Native Promise Docs - MDN

For your particular question, imo, the npm module request-promise offers some great solutions. 对于您的特定问题,imo,npm模块请求 - 承诺提供了一些很好的解决方案。 It is essentially a 'Promisified" version of the request module: 它本质上是请求模块的“Promisified”版本:

It will allow you to GET/POST/PUT/DELETE and follow up each request with a . 它将允许您进行GET / POST / PUT / DELETE并使用a跟进每个请求。 then() where you can continue to do more calls like so: then()你可以继续做更多的调用:

-this code first GETS something from a server, then POSTS something else to that server. - 这个代码首先从服务器获取一些内容,然后向该服务器发送其他内容。

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

You can just keep going with the .then() whatever you return from the previous .then() will be passed in to the function. 你可以继续使用.then()无论你从前一个返回.then()将被传递给函数。

Request-Promise 请求承诺

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

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