我的许多 friend 在他们的库中深入使用了一些 deferred/promises 对象,他们经常告诉我,在自己的实现中使用计时器是一种邪恶。
它不对应于 A+:https://github.com/promises-aplus/promises-spec
许多库(如 jQuery 和其他库)不使用计时器。所以我试图在 jQuery 源中找到任何可能与 Promise 实现相关的计时器,但没有成功:
https://github.com/jquery/jquery/blob/master/src/deferred.js
好吧,但是我在 A+ 描述中发现了一些注释,这让我对在其中使用计时器感到困惑:
在注释
文章中:
Here "platform code" means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack. This can be implemented with either a "macro-task" mechanism such as setTimeout or setImmediate, or with a "micro-task" mechanism such as MutationObserver or process.nextTick. Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or "trampoline" in which the handlers are called.
所以,我知道 A+ 对于计时器的使用没有严格的规则,或者确实如此?
帮帮我,我很困惑。
最佳答案
您将 setTimeout
的使用与“设置计时器”混淆了 - Promises/A+ 实现通常使用 setTimeout
来保证异步执行处理函数,不延迟执行一段时间。
Promises/A+ 保证异步调用已完成和已拒绝的方法,无论何时完成 Promise。在浏览器 JS 环境中保证异步执行的一种方法是将函数调用包装在 setTimeout
中,超时时间为零(默认值)。
jQuery 不保证异步执行已完成/已拒绝的回调(即 a major design flaw ),因此不需要异步包装器调用。
关于javascript - 在延迟/ promise 实现中使用计时器是一种邪恶吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26487439/