为什么要使用 Promise.resolve().then()? [英] Why to use Promise.resolve().then()?

查看:42
本文介绍了为什么要使用 Promise.resolve().then()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 Angular 指令的代码时 RouterLinkActive,我发现了一个奇怪的Promise.resolve用法:

While reading Angular's code for the directive RouterLinkActive, I found a curious usage of Promise.resolve:

  private update(): void {
    ...
    Promise.resolve().then(() => {
      const hasActiveLinks = this.hasActiveLinks();
      if (this.isActive !== hasActiveLinks) {
        ...
      }
    });
  }

在哪种情况下,使用 Promise.resolve().then() 而不是只执行 then 内部的代码有用吗?

In which case is it useful to use Promise.resolve().then() instead of just executing the code that is inside of the then?

我见过 setTimeout(() => defeferedFunction()) 的用法,但第一次用 Promise.resolve 看到它.

I've seen usages of setTimeout(() => defeferedFunction()) but first time seeing it with Promise.resolve.

推荐答案

Angular 框架做了很多这件事.它用于防止您会看到很多错误(对不起,不知道错误的实际措辞),例如检查后值已更改".如果更改检测器检查了一个值,然后在同一周期内更改了该值,则会发生此错误.

The Angular framework does this a lot. It is used to prevent an error that you will see a lot (sorry don't know the actual wording of the error) something like 'The value was changed after it was checked'. This error happens if the Change Detector checked a value and then it was changed in the same cycle.

Promise.resolve() 将此代码推送到微任务队列,以便在 JavaScript 堆栈为空后执行.这可以防止错误.

The Promise.resolve() pushes this code on to the microtask queue so it is executed after the JavaScript stack is empty. This prevents the error.

这篇关于为什么要使用 Promise.resolve().then()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆