繁体   English   中英

在避开Try / Catch块时异步/等待?

[英]Async/Await while avoiding the Try/Catch block?

我一直在使用Node大约一个月左右,我想利用可用的最新功能,比如Async / Await样式,但我不喜欢使用try / catch块。 我一直在尝试创建一些包装类和/或函数来包装async / await。

我使用await-to-js npm模块的解构逻辑来部分缓解try / catch的使用,但是我有点困惑如何在不使用es6 promise的情况下在异步函数之外使用它,我怎么能链多个等待使用这种方法?

任何帮助,建议或批评,如果我做了一些完全错误的事情,我们不胜感激。

避免在async/await使用try/catch块的一个好方法是为错误处理创建一个高阶函数:

function catchErrors(fn) {
  return function(...args) {
    return fn(...args).catch((err) => {
      console.error(err);
    })
  }
}

async function asyncFunc(name, value) {
  const a = await ...
  const b = await ...
  /* ... */
}

// Wrap it in an higher-order function
const wrappedAsyncFunc = catchErrors(asyncFunc);

wrappedAsyncFunc("lala", 4);

你必须选择。 使用trycatch block或使用promises。 async / await的原因存在于那些不喜欢promises并且更喜欢更清晰的代码的人。

如果你不想要两者,你可以使用

https://nodejs.org/api/process.html#process_event_uncaughtexception

要么

https://nodejs.org/api/process.html#process_event_unhandledrejection

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM