Reputation: 19163
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
Upvotes: 22
Views: 50266
Reputation: 13532
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
You can also use the built-in fetch API that comes with latest versions of nodejs(18+). See below for an example.
async function funcOne(input) {
try {
const response = await fetch(someUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(input),
});
if (response.ok) {
const body = await response.json();
funcTwo(body, (err, output) => {
console.log(err, output);
});
}
} catch (err) {
// Handle errors here
console.error(err);
}
}
function funcTwo(input, callback) {
// process input
callback(null, input);
}
Upvotes: 16
Reputation: 123
Since request is deprecated. I recommend working with axios.
npm install [email protected]
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
Upvotes: 6