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

So, looking at the documents with promises, promises, that's what I

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 the 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 correct / correct, but I cannot figure out how to return it as a value.

+5
source share
2 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 as follows:

 get_data_id('hello').then(function (id) { console.log('Got the following id:', id) }) 
+4
source

I think because the promise-promise will return the promise.

So, if you directly return console.log the value will be undefined because the promise is not yet resolved.

+2
source

Source: https://habr.com/ru/post/1246648/


All Articles