Bluebird 的 Promise.try
函数有其他替代方案吗?因为我正在使用 async/await
对添加 bluebird 依赖项不感兴趣。
有没有更好的方法来捕获Node.JS
中的异步错误
await Promise.try(async function() {
// Some code with async operations like readline
await this.nextCall(batchData, true);
}).catch(async function(err) {
// My error handling
});
Node.js 10.x 中有内置函数吗?
更新:
有没有更好的方法来捕获Node.JS
中的异步错误
try {
let interfaceVal = lineReader.createInterface({
input: fs.createReadStream(filePath)
});
interfaceVal.on('line', async (line) => {
throw new Error('My custom Error');
});
// some sync operations
} catch(e) {
// This catch won't get called with custom error
console.log(e);
}
有办法捕获此类异步错误吗?
最佳答案
没有理由用 Promise.try
包装 async
函数。 Promise.try
的目的是类似地处理同步错误和拒绝:
Start the chain of promises with Promise.try. Any synchronous exceptions will be turned into rejections on the returned promise.
这已经通过 async
完成,因为它总是返回一个 promise 。
这可以在顶层与async
IIFE一起使用:
(async function() {
await this.nextCall(batchData, true);
})().catch(console.error);
或者,如果async
嵌套,则可以省略它,可以在父async
函数中使用try..catch
处理拒绝,正如另一个答案所解释的。
在这种情况下,只能在 async
函数内部捕获错误:
interfaceVal.on('line', async (line) => {
try {
throw new Error('My custom Error');
} catch (err) {
console.error(err);
}
});
使用非 promise API( Node 流)不允许使用 promise 进行错误处理。流回调忽略被拒绝的 promise ,并且不允许将错误传播到流之外。
只有当回调预计被调用一次
时,才能将其转换为promise。 line
的情况并非如此。在这种情况下可以使用异步迭代器,this one of its use cases .
事件发射器可以通过 p-event
转换为异步迭代器并在 async
函数中使用 for wait of
进行迭代:
try {
let interfaceVal = lineReader.createInterface({
input: fs.createReadStream(filePath)
});
const asyncIterator = pEvent.iterator(interfaceVal, 'line', {
resolutionEvents: ['close']
});
for await (const event of asyncIterator) {
console.log('line', event);
// throw new Error('My custom Error');
}
} catch(e) {
console.log(e);
}
关于node.js - 如何处理 Node.js 中的异步错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52837091/