When I use request-promise in a function and return a value it says undefined
11,104
Solution 1
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)
})
Solution 2
I think it's because the request-promise will return a promise.
So if you directly console.log the return value, it will be undefined, because the promise has not yet been resolved.
Related videos on Youtube
Author by
cantsay
Updated on July 11, 2022Comments
-
cantsay almost 2 years
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
toconsole.log(JSON.parse(response).id)
I get the followingundefined 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.
-
Nate S over 4 yearsthanks I was able to use this to send another request() as I was having trouble making a GET request then sending the returned body to a webhook with a POST request