0

I would like to use request-promise module and do something with response body. However i am not able to make response available outside request-promise scope.

var rp = require('request-promise');

rp('http://www.google.com')
    .then(function (response) {
        let variable = response;
    })
    .catch(function (err) {
        // rejected
});

console.log(variable); // this will not work right? then, how to make it work in easy way?

Thank you for help.

3 Answers3

0

The process will work asynchronously so your variable will always be undefined or it might throw an error if you declared it inside the async function .

The best approach will be to use async await

var rp = require('request-promise');
async function getData()
{

let variable=await rp("http://www.google.com");
console.log(variable) // do anything with your variable
}


getData();

You would like to see this

Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
0

3 options for you.

Example 1


const rp = require("request-promise");

rp("http://www.google.com")
  .then(res => {
    // you can use response here
  })
  .catch(e => console.log(e));

Example 2

const rp = require("request-promise");

rp("http://www.google.com")
  .then(res => restOfMyCode(res))
  .catch(e => console.log(e));

const restOfMyCode = result => {
  console.log(result);
};

Example 3

const rp = require("request-promise");

(async () => {
  try {
    const result = await rp("http://www.google.com");
    console.log(result);
  } catch (e) {
    console.log(e);
  }
  console.log(result)
})();
0

Thank you both guys you inspired me to final solution which at the moment looks like this:

const rp = require('request-promise');

(async () => {

    var data = await getData();
    console.log(JSON.stringify(data, null, 2));     


    async function getData() {
            var options = {
                uri: 'https://www.google.com',
                json: true
            };
            var variable=await rp(options);
            return variable; // do anything with your variable
    }

}
) ();