较新的 node js 有 async await,这真的很酷,因为它使代码看起来更好。
我想知道让每个类方法异步是否是个好主意,即使它不需要返回 promise ?
在我的用例中,我实际上有点需要它,因为我试图在多个子进程之间共享依赖关系,并且我正在使用代理和子进程通信的组合来实现这一点。显然我需要 promise ,因为我需要等待进程响应或发送消息。
但这是否有任何潜在的副作用,也许是长期的?
更清楚地说,我这样做只是为了酷炫的语法。
const database = CreateProxy('database');
await database.something();
来自另一个进程。
与一些只从父进程请求东西
的代码相比
process.send('getSomethingFromDb');
在引擎盖下两者都使用消息传递,但第一个使表面上看起来好像没有
此概念是 Occam's razor 的主题.没有好处,但可能有缺点。
额外开销(CPU 和时间)是问题之一。 promise 需要一些时间和资源来解决。这可能需要不到一毫秒的时间,但延迟会累积。
另一个问题是异步性是会传染的,一旦它到达模块范围,async
IIFE 应该到处使用 - 因为 top-level await
尚不支持:
module.export = (async () => {
await require('foo');
// await was accidentally dropped
// this results in race condition and incorrect error handling
require('foo');
...
})();
下面是一个使错误处理复杂化的缺点的好例子:
async function foo() {
throw new Error('foo');
}
async function bar() {
try {
return foo();
} catch (err) {
console.log('caught with bar');
}
}
bar(); // UnhandledPromiseRejectionWarning: Error: foo
尽管在 async
中控制流看起来像同步的,但错误的处理方式不同。 foo
返回被拒绝的 promise,并且返回值不会在 async
函数中用 try..catch
处理。 bar
不会处理拒绝。
常规函数不会发生这种情况:
function foo() {
throw new Error('foo');
}
function bar() {
try {
return foo();
} catch (err) {
console.log('caught with bar');
}
}
bar(); // caught with bar
对于设计为同步工作的第三方库,事情可能会变得更加复杂。