当我在函数中使用request-promise并返回一个值时,它表示未定义

can*_*say 9 request node.js

因此,通过查看请求承诺文档,这就是我所拥有的

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

然后我在我的脚本中的其他地方使用此代码

console.log(get_data_id(searchValue));

然而它又回来了undefined.

如果我改为return JSON.parse(response).id,console.log(JSON.parse(response).id)我会得到以下内容

undefined
valueofID
Run Code Online (Sandbox Code Playgroud)

所以我试图返回的值肯定是有效/正确的,但我无法弄清楚如何将其作为值返回.

idb*_*old 11

您需要将承诺返回给调用者:

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

然后像这样使用你的函数:

get_data_id('hello').then(function (id) {
  console.log('Got the following id:', id)
})
Run Code Online (Sandbox Code Playgroud)


Vil*_*oja 2

我认为这是因为请求承诺会返回一个承诺。

所以如果你直接console.log返回值,它将是未定义的,因为promise还没有被解析。