Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I use request-promise in a function and return a value it says undefined

So from looking at the request-promise docs, here is what I have

function get_data_id(searchValue) {
    rp('http://example.com?data=searchValue')
    .then(function(response) {
        return JSON.parse(response).id;
    });
}

And then I use this code elsewhere in my script

console.log(get_data_id(searchValue));

However it returns undefined.

If I change return JSON.parse(response).id to console.log(JSON.parse(response).id) I get the following

undefined
valueofID

So the value I'm trying to return is definitely valid/correct, but I can't figure out how to return it as a value.

like image 514
cantsay Avatar asked Apr 07 '16 19:04

cantsay


1 Answers

You need to return the promise to the caller:

function get_data_id(searchValue) {
  return rp('http://example.com?data=searchValue')
    .then(function(response) {
      return JSON.parse(response).id;
    });
}

Then use your function like this:

get_data_id('hello').then(function (id) {
  console.log('Got the following id:', id)
})
like image 141
idbehold Avatar answered Oct 21 '22 05:10

idbehold