I need to get the responses from three http requests serially in their order.
I was able to do this with nested functions. I also need to use the response from the last request in the global scope, which i am not able to do with the nesting solution.
var request = require("request");
httpRequest1((getRequest1) => {
console.log(getRequest1);
httpRequest2((getRequest2) => {
console.log(getRequest2);
httpRequest3((getRequest3) => {
console.log(getRequest3);
});
});
});
function httpRequest1 (callback){
var options = { method: 'POST',
url: };
request(options, function (error, response, body) {
if (error) throw new Error(error);
callback (body);
});}
function httpRequest2(callback){
var options = { method: 'POST',
url: };
request(options, function (error, response, body) {
if (error) throw new Error(error);
callback(body);
});}
function httpRequest3(callback){
var options = { method: 'POST',
url: };
request(options, function (error, response, body) {
if (error) throw new Error(error);
callback(body);
});}
function httpRequest1 (callback){
var options = { method: 'POST', url: };
return new Promise(function (resolve, reject) {
request(options, function (error, response, body) {
if (error) return reject(error);
resolve(body);
});
});
}
function httpRequest2 (callback){
var options = { method: 'POST', url: };
return new Promise(function (resolve, reject) {
request(options, function (error, response, body) {
if (error) return reject(error);
resolve(body);
});
});
}
function httpRequest3 (callback){
var options = { method: 'POST', url: };
return new Promise(function (resolve, reject) {
request(options, function (error, response, body) {
if (error) return reject(error);
resolve(body);
});
});
}
Promise
httpRequest1()
.then(body1 =>
return httpRequest2();
)
.then(body2 =>
return httpRequest3();
)
.then(body3 =>
).catch(error => {
// error code
} );
Async/Await
function async getResponse() {
try {
const body1 = await httpRequest1();
const body2 = await httpRequest2();
const body3 = await httpRequest3();
} catch (e) {
console.log(e);
}
}
updated
Await doesn't work at normal function. If you use await , you must have to use it in a asyn function . If you want to call serialize async functions from a normal function , then promise is better option. But you may use another way. Suppose we have a async function like above with return of response
function async getResponse() {
try {
const body1 = await httpRequest1();
const body2 = await httpRequest2();
const body3 = await httpRequest3();
return { body1, body2, body3 }
} catch (e) {
console.log(e);
}
}
function normalFunction() {
// const res = getResponse(); it will not work
getResponse()
.then(result => {
// you will get the result here
})
}
under the hood async function return promise Result . thats why we can write such way.