Ale*_*lex 4 javascript asynchronous child-process node.js promise
较新的节点js具有async等待,这真的很酷,因为它使代码看起来更好。
我想知道让每个类方法都异步是个好主意,即使它不需要返回承诺也是如此吗?
在我的用例中,我实际上有点需要,因为我试图在多个子进程之间共享依赖关系,并且我使用了代理和子进程通信的组合来实现这一点。显然,我需要承诺,因为我需要等待流程响应或发送消息。
但这是否可能有长期的潜在副作用?
更明确地说,我仅是出于酷语法的目的而执行此操作。
const database = CreateProxy('database');
await database.something();
Run Code Online (Sandbox Code Playgroud)
从另一个过程。
与一些something仅从父进程请求的代码(例如
process.send('getSomethingFromDb');
Run Code Online (Sandbox Code Playgroud)
两者都使用消息传递,但是第一个使它看起来好像不在表面上
这个概念是奥卡姆剃刀的主题。没有好处,但有缺点。
问题之一就是额外的开销(CPU和时间)。承诺需要一些时间和资源来解决。这可能会花费不到一毫秒的时间,但可能会滞后。
另一个问题是异步性具有传染性,一旦到达模块范围,asyncIIFE就应在所有地方使用-因为尚不支持顶层await:
module.export = (async () => {
await require('foo');
// await was accidentally dropped
// this results in race condition and incorrect error handling
require('foo');
...
})();
Run Code Online (Sandbox Code Playgroud)
这是使错误处理复杂化的劣势的一个很好的例子:
async function foo() {
throw new Error('foo');
}
async function bar() {
try {
return foo();
} catch (err) {
console.log('caught with bar');
}
}
bar(); // UnhandledPromiseRejectionWarning: Error: foo
Run Code Online (Sandbox Code Playgroud)
尽管控制流程看起来像是同步的async,但错误的处理方式却有所不同。foo返回拒绝的承诺,并且返回的值不使用try..catchin async函数处理。拒绝将不会在中处理bar。
使用常规函数不会发生这种情况:
function foo() {
throw new Error('foo');
}
function bar() {
try {
return foo();
} catch (err) {
console.log('caught with bar');
}
}
bar(); // caught with bar
Run Code Online (Sandbox Code Playgroud)
使用旨在同步工作的第三方库,事情可能会变得更加复杂。
我想知道使每个类方法异步是否是个好主意,即使它不需要返回承诺?
你的代码可以工作,但我不推荐它有两个原因:
不必要的内存/cpu 使用
它会使您的代码难以理解。知道哪个函数是异步的或同步的对于理解系统如何工作以及它在做什么很重要。
小智 4
调用函数的结果async将始终是 a Promise,无论函数是否实现任何异步行为。
const asyncTest = async () => 3;\nconsole.log(asyncTest()); // logs 'Promise\xc2\xa0{<resolved>: 3}'\nRun Code Online (Sandbox Code Playgroud)\n\n因此,您必须始终确保使用await. 但这纯粹是一个舒适度问题,即使对你来说也是如此。而且,创建和解析 Promise 会为每个函数调用增加一点时间,因此如果性能至关重要,您应该避免调用async大量调用函数(如果可以避免的话)。
| 归档时间: |
|
| 查看次数: |
689 次 |
| 最近记录: |