0

I'm working on a node.js app and using Request to get data from an API, using this function:

function do_request( method, path, body ){

  var options = {
      ...
  };

  request( options, function(err, response, body){

      if (err) console.log(err);

      return JSON.parse(response.body);

  });

}

I want to be able to save the returned value to a variable - something like this:

var products = do_request('GET','/products','');

At the moment, if I console.log(products) after the code above, I get undefined.

From what I've found from googling, it looks like it's probably async-related. I've tried using promises and asyncing functions based on some examples/solutions I found but I'm a node noob and couldn't get it working. Any ideas?

AJT
  • 216
  • 2
  • 6
  • 31

3 Answers3

1

Try to promisify the request library and call the do_request inside an async function (since you can await promises inside async functions)


function do_request( method, path, body ){

  var options = {
      ...
  };

  return new Promise((resolve,reject)=>{
    request( options, function(err, response, body){
      if (err) reject(err);
      resolve(JSON.parse(response.body));
  });
  }) 

}


async function main_code(){
  try{
     var products = await do_request('GET','/products',''); 
     }
  catch(e){
     // exception handling
     }
  finally{
     // stuff to do anyway, cleanups etc etc.
    }
}

main_code();

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
0

the async version would look like that:

async function do_request( method, path, body ){

  var options = {
      ...
  };

  await request( options, function(err, response, body){

      if (err) console.log(err);

      return JSON.parse(response.body);

  });

}

Or since Request is deprecated you could / (should?) use something like axios:

axios.get("request_url").then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
PixAff
  • 309
  • 4
  • 14
  • You would have to wrap the NPM package as request by itself doesn't return a promise. https://www.npmjs.com/package/request#promises--asyncawait – James Apr 05 '21 at 17:22
0

You have to make your function an asynchronous function by adding async key word and you can call your function with await keyword.

Then when the request is fulfilled without errors. You can see your products variable with some meaningful value.

If you are just printing your products variable right after the function call line. It will be undefined as the request has not been fulfilled by that time.

What you can opt for, is to use .then (callback) instead of await keyword. So when your request is returned, then your product variable will be filled and you can print it then. Something like this:

do_request('GET','/products','').then((returning_value)=>{console.log(returning_value})
mani9418
  • 141
  • 1
  • 1
  • 9