3

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

3
  • This is a largely subjective thing, but my take is to use Promises to organize your callback code. Commented Apr 19, 2016 at 20:44
  • Check this out :) npmjs.com/package/rx Commented Apr 19, 2016 at 20:57
  • @mark the answers offered complement each other and would work well in tandem. Commented Apr 19, 2016 at 21:03

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.