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

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

问题描述

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

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

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

根据规范,Promise 可以成为其中之一:

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:

  • Promise 确定了吗?

  • is the Promise settled?

如果是,Promise 是否已解决?

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 中编写代码)em>) 然后你可以使用特定的工具(比如私有符号)来实现这一点.不过,这是非常具体的,而不是在用户领域.

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天全站免登陆