Node.js Pomise异步方法返回未定义

时间:2019-05-13 07:08:24

标签: node.js promise get async-await

我已经使用promise创建了一个node.js应用程序。我有以下代码

async clientCall() {

    const baseUrl = 'https://localhost:44300/test';
    const queryString = '';
    var options = {
        uri: baseUrl + queryString,
    };
    process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
    var result =  await request.get(options, function (err: any, res: any, body: any) {
        console.log("Result: ", body)
        return body;
    })

     console.log("response:",result);
    // return result;
}

await ClientRepository.clientCall().then(data => {

    console.log("inside data: ",data)

    return data;
})

但是我得到了这样的输出

response:
Result: My response
inside data: undefined
inside data: My response

我仅在等待请求完成后才返回响应。

1 个答案:

答案 0 :(得分:1)

我认为以下是您的解决方案。如果将Promise传递给await表达式,它将等待Promise被实现并返回被实现的值。

async function clientCall() {
    return new Promisse((resolve, reject) => {
        const baseUrl = 'https://localhost:44300/test';
        const queryString = '';
        var options = {
            uri: baseUrl + queryString,
        };
        process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
        request.get(options, function (err: any, res: any, body: any) {
            resolve(body);
        })
    });
}

async function callClientCall(){
    let clientCallResult = await ClientRepository.clientCall();
}

简单的例子:

function resolveAfter2Seconds(x) { 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}
f1();