使用await时如何获得错误和结果

时间:2016-11-27 10:19:12

标签: javascript node.js promise async-await

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

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);

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

1 个答案:

答案 0 :(得分:1)

await的重点是将异步代码展平为同步代码,这会导致出现错误(例如JSON.parse
等待异步函数时 - 如果异步函数返回结果 - 它返回就像函数是同步的一样,
如果异步函数抛出异常 - await重新抛出它,就好像该函数是同步的一样。

所以,首先,没有“状态”,只有例外。您应该使用await / try

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

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