当我在一个函数中使用request-promise并返回一个值时,它说undefined
所以从查看请求承诺文档,这里是我所拥有的
function get_data_id(searchValue) { rp('http://example.com?data=searchValue') .then(function(response) { return JSON.parse(response).id; }); }
然后我在脚本的其他地方使用这个代码
console.log(get_data_id(searchValue));
但是它返回undefined
。
如果我更改return JSON.parse(response).id
到console.log(JSON.parse(response).id)
我得到以下
undefined valueofID
所以我试图返回的值肯定是有效/正确的,但我不知道如何将它作为一个值返回。
我想这是因为请求承诺会返回一个承诺。
所以,如果你直接console.log返回值,它将是未定义的,因为承诺尚未解决。
您需要将承诺退还给调用者:
function get_data_id(searchValue) { return rp('http://example.com?data=searchValue') .then(function(response) { return JSON.parse(response).id; }); }
然后使用你的这个function:
get_data_id('hello').then(function (id) { console.log('Got the following id:', id) })