gpt4 book ai didi

Node.js 控制流 : callbacks or promises?

转载 作者:IT老高 更新时间:2023-10-28 22:12:06 26 4
gpt4 key购买 nike

我知道有很多control flow libraries对于 node.js。其中一些让一个链异步函数与回调(如 async、asyncblock 等),其他使用 promise concept (Q、延期、 future 等)。给定一个长时间运行的脚本,一个接一个地执行一系列可能随时失败的操作,您更喜欢哪个控制流,为什么?有什么好处和坏处?

最佳答案

回调的优点:

  • 简单易于理解和创造。
  • 稍微更高效,因为创建和垃圾收集的对象更少。
  • Node 自始至终都选择了 (error,result) 回调。我建议遵循他们的论点顺序以保持一致性。 (相对于说 (result1, result2, result3, error)。)

promise 的优点:

  • 提供流畅的界面,有时可以帮助缓解嵌套回调 hell ,如shown here .通过链接 .then(foo).then(bar) 调用,代码似乎呈线性流动。
  • 一个好的 promises 库可以让你并行运行许多异步操作,并且只有在它们都完成后才能继续。 Deferred库通过 map 无缝地做到这一点,Q 有 allResolved,ES6 Promises 提供 Promise.all()。 (这也可以通过回调实现,例如使用 async.parallel(),但不是内置的。)
  • 一个好的 Promise 库可以让你指定一个错误处理函数,如果任何排队的函数失败,就会调用该函数。要使用回调执行此操作,需要一些样板:if (err) return callback(err); 在每个回调的开头。

堆栈底部附近使用回调是有意义的,因为代码每秒会运行很多次。在堆栈的更高层,promise 可能更受欢迎,因为它们更易于阅读和理解,并且可以更优雅地处理错误。

值得注意的是,promise 可以在运行时从回调构建。因此,您可以以极简的回调形式实现您的核心代码,并且如果您愿意,仍然可以公开该库的 Promise 版本。 (如 Q.nfbind()。)

我很想听听其他优点/缺点。

Bonus tip: Always handle errors! With both methods, if you do not handle the error then it will simply disappear, leaving you in the dark about why your code did not work as expected.

Callbacks should always handle if (err) ... and Promises should always have a .catch() if they do not return.

Even if you expect errors sometimes, and don't need to handle those, not handling unexpected errors means you won't hear about errors from developer mistakes such as typos, if the code is changed in future.

An alternative to .catch() for Promises is to listen for unhandled rejections. Personally I use this to issue a warning that .catch() was missing!

关于Node.js 控制流 : callbacks or promises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9391396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com