javascript - 在延迟/ promise 实现中使用计时器是一种邪恶吗?

标签 javascript asynchronous timer promise deferred

我的许多 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/

相关文章:

javascript - 从哪里 Javascript 错误 "ReferenceError: Can' t 找到变量 : imenu_title"?

asynchronous - 当任务已经在 python3.7 的 asyncio 库中运行时,如何将任务添加到事件循环?

javascript - 通用 promise 重试逻辑

ios - 按下时禁用按钮 30 秒,再次启用,然后再次按下时禁用

javascript - 无法在浏览器中打开新标签页?

javascript - 在后台加载第二个网页以从此网页获取内容

javascript - JS - 如何计算二进制数据的 MD5

multithreading - Lwt.async() 未按预期工作

java - 在 Scheduler(Timer) 的 run 方法中创建 Scheduler(Timer)

java - 我如何创建一个使用 swing 进行计数的计时器