1

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);
  });}
Guy Perry
  • 23
  • 4
  • That *is* how you do it. If you need the final result, you access it in the callback. Alternatively, look into promises. – jonrsharpe Aug 11 '19 at 10:48
  • 1
    I recommend to use **Promose** or **Async/Await** . Avoid callback bacause it may occurs callback hell . – Rahul Aug 11 '19 at 10:50
  • How would you implement Async/Await? When I tried to use Async/Await I get an undefined response, as if it is not really waiting for the request to complete. – Guy Perry Aug 11 '19 at 11:05

4 Answers4

0

You should consider the more modern async/await pattern and use it to resolve promises. It will make your code more readable to yourself and others.

Read this blog for more details, specifically the "Chaining Operations" section in your case: https://www.sitepoint.com/simplifying-asynchronous-coding-async-functions/

mprivat
  • 20,572
  • 4
  • 51
  • 62
0
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.

Rahul
  • 191
  • 5
  • Thanks, the Async/Await code worked, but I still have a problem. if I try to use the body1-3 arguments outside the Async function, it happens before the async function finishes and I get that they are undefined. – Guy Perry Aug 11 '19 at 14:36
  • @GuyPerry updated , You may have a look – Rahul Aug 11 '19 at 17:32
0
var request = require("request-promise");
( async () => {
    const getRequest1 = await httpRequest1();
    const getRequest2 = await httpRequest2();
    const getRequest3 = await httpRequest3();
})();

async function httpRequest1() {
    var options = {
        method: 'POST',
        url: ''
    };
    const body = await request(options)
    if (!body) throw "error";
    return body;
}

async function httpRequest2() {
    var options = {
        method: 'POST',
        url: ''
    };
    const body = await request(options)
    if (!body) throw "error";
    return body;
}

async function httpRequest3() {
    var options = {
        method: 'POST',
        url: ''
    };
    const body = await request(options)
    if (!body) throw "error";
    return body;
}
Nayan Patel
  • 1,377
  • 18
  • 26
0

If the requests are independent, you can use Promise.all(). You don't have to wait for the response of httpRequest1 before calling httpRequest2 and so on.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Swarup Bam
  • 156
  • 8