如何同步确定JavaScript Promise的状态? [英] How can I synchronously determine a JavaScript Promise's state?

查看:125
本文介绍了如何同步确定JavaScript Promise的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个纯JavaScript Promise(内置实现或poly-fill):

I have a pure JavaScript Promise (built-in implementation or poly-fill):

var promise = new Promise(function(resolve) ,拒绝){/ * ... * /});

来自规范,承诺可以是以下之一:

From the specification, a Promise can be one of:


  • '已结算'和'已解决'

  • '已结算'和'已拒绝'

  • '待定'

我有一个用例,我希望同步询问Promise并确定:

I have a use case where I wish to interrogate the Promise synchronously and determine:


  • 承诺已落户吗?

  • is the Promise settled?

如果是,是否已解决承诺?

if so, is the Promise resolved?

我知道我可以使用 #then() 安排在Promise更改状态后异步执行的工作。我不是在问这个怎么做。

I know that I can use #then() to schedule work to be performed asynchronously after the Promise changes state. I am NOT asking how to do this.

这个问题具体是关于对Promise状态的同步询问。我怎样才能实现这一目标?

This question is specifically about synchronous interrogation of a Promise's state. How can I achieve this?

推荐答案

本机JavaScript承诺不存在此类同步检查API。它用本机的承诺是不可能的。规范没有指定这样的方法。

No such synchronous inspection API exists for native JavaScript promises. It is impossible to do this with native promises. The specification does not specify such a method.

Userland库可以做到这一点,如果你的目标是特定的引擎(如v8)并且可以访问平台代码(也就是说,您可以在 core 中编写代码)然后您可以使用特定工具(如私有符号)来实现此目的。这是超级特定的,而不是用户区。

Userland libraries can do this, and if you're targeting a specific engine (like v8) and have access to platform code (that is, you can write code in core) then you can use specific tools (like private symbols) to achieve this. That's super specific though and not in userland.

这篇关于如何同步确定JavaScript Promise的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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