【问题标题】:Is it possible to execute code while a Promise's status is pending? [closed]是否可以在 Promise 的状态未决时执行代码? [关闭]
【发布时间】:2020-11-24 18:28:08
【问题描述】:

通常,期望的行为是开发人员希望确保在特定承诺被履行或拒绝之前不会执行其他代码。现在,使用 async / await 模式很容易实现。

但是,我有一种情况,需要同时执行其他代码,而 Promise(很可能会成功解决!)。这就是为什么我没有在目的上设置等待修饰符的原因;到目前为止,一切都很好。但是,当承诺的状态是“待定”而不是“已解决”时,如何确保在时间窗口内执行一段代码?比如,在不知道它是否被拒绝之前?

我想像一个 while 循环,但由于 [[PromiseStatus]] 属性不可访问,我需要每次都输入 'then' 才能访问承诺值,并且无休止地使用 (then) '似乎不是真正可行的解决方案。

我们将不胜感激。

【问题讨论】:

  • 这就是 Promises 的工作原理。
  • 欢迎来到 Stack Overflow!请the tour(你得到一个徽章!)并通读help center,特别是good question?你最好的选择是做你的研究,search关于SO的相关主题,然后试一试。如果您在进行更多研究后卡住并且无法摆脱卡住,请发布您的尝试Verifiable Example,并具体说明您卡在哪里。人们会很乐意提供帮助。

标签: javascript typescript asynchronous promise


【解决方案1】:

这就是 Promise 的原生工作方式。您可以通过不使用 await 关键字来启动它们,然后在准备好时使用 await 。下面的演示展示了这一点。

async function dummyPromise(){
  return new Promise(resolve => setTimeout(resolve,3000));
}

async function test(){
   var prom = dummyPromise();
   console.log("This line runs while the promise is pending");
   await prom;
   console.log("This line runs after the promise resolves");

}

test();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2012-01-04
    • 1970-01-01
    • 2013-01-05
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多