【问题标题】:How to get err and result when using await使用等待时如何获取错误和结果
【发布时间】:2017-04-11 04:52:21
【问题描述】:

我有一个接收回调作为参数的函数。例如:

client.sendMessage(params, (status, response) => {
  console.log('Status: ', status);
  console.log('API Response:\n', response);
});

然后我答应它:

const Promise                 = require('bluebird');
const sendMessageFunc: Object = Promise.promisify(client.sendMessage);

那我叫它:

result = await sendMessageFunc(params);

我实际上想得到(status, response) 然后这样做:

(status, response) = await sendMessageFunc(params);
console.log('Status: ', status);
console.log('API Response:\n', response);

但这不是有效的语法。我该怎么办?返回给我的“结果”对象是什么?

【问题讨论】:

    标签: javascript node.js promise async-await


    【解决方案1】:

    await 的全部意义在于将您的异步代码扁平化,使其像同步代码一样在发生错误时抛出(例如 JSON.parse
    等待异步函数时 - 如果异步函数返回结果 - 就好像函数是同步的一样返回,
    如果异步函数抛出异常 - await 重新抛出异常,就好像函数是同步的一样。

    所以,首先,没有“状态”,只有例外。你应该用try/catch包围你的await表达式:

    try{
        let response = await sendMessageFunc(params);
        console.log('API Response:\n', response);
    }
    catch(e){
        console.error('an error was thrown: ' + e.toString());
    }
    

    promise 只是实现协程(这是 async/await 关键字实际创建的)的便捷工具。使用await 时不要考虑承诺,这只是一个实现细节。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-22
      • 2015-11-07
      • 2011-09-03
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      相关资源
      最近更新 更多