简体   繁体   中英

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

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.

Thanks for any hints / guidelines, Mark

Maybe check out the Async library. 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

Agreed that this is subjective, in general the way to go is promises, there are native promises:

Native Promise Docs - MDN

For your particular question, imo, the npm module request-promise offers some great solutions. It is essentially a 'Promisified" version of the request module:

It will allow you to GET/POST/PUT/DELETE and follow up each request with a . then() where you can continue to do more calls like so:

-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.

Request-Promise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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