22

I am using NodeJS. One of my function (lets call it funcOne) receives some input which I pass to another function (lets call it funcTwo) which produces some output.

Before I pass the input to funcTwo I need to make an Ajax call to an endpoint passing the input and then I must pass the output produced by the AJAX call to funcTwo. funcTwo should be called only when the AJAX call is successful.

How can I achieve this in NodeJS. I wonder if Q Library can be utilized in this case

SharpCoder
  • 18,279
  • 43
  • 153
  • 249

2 Answers2

16

Using request

function funcOne(input) { 
  var request = require('request');
  request.post(someUrl, {json: true, body: input}, function(err, res, body) {
      if (!err && res.statusCode === 200) {
          funcTwo(body, function(err, output) {
              console.log(err, output);
          });
      }
  });
}

function funcTwo(input, callback) {
    // process input
    callback(null, input);
}

Edit: Since request is now deprecated you can find alternatives here

Barış Uşaklı
  • 13,440
  • 7
  • 40
  • 66
5

Since request is deprecated. I recommend working with axios.

npm install axios@0.16.2

const axios = require('axios');

axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
  .then(response => {
    console.log(response.data.url);
    console.log(response.data.explanation);
  })
  .catch(error => {
    console.log(error);
  });

Using the standard http library to make requests will require more effort to parse/get data. For someone who was used to making AJAX request purely in Java/JavaScript I found axios to be easy to pick up.

https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

Gautam Mehta
  • 113
  • 1
  • 4