当关键字后面的表达式没有评估为承诺时,`await`会发生什么? [英] What should happen with `await` when the expression after the keyword does not evaluate to promise?
问题描述
我有这样的ES7代码。
I have a ES7 code like this.
async function returnsfive() {
var three = 3;
var threeP = await three;
return threeP+2;
}
returnsfive().then(k=>console.log(k), e=>console.error("err", e))
在 var threeP =等待三个
行会发生什么?
如果代码按预期继续,或者失败,因为三
不是承诺?
Should the code continue as expected, or fail, because three
is not a promise?
在此回购中,它被称为Debatable Syntax& amp; ;语义学。我无法阅读官方文档以找到确切的定义,因为它太技术性了。
In this repo, it is mentioned as "Debatable Syntax & Semantics". I am not able to read through the official documentation to find the exact definition, since it's too technical.
默认babel.js转换日志5按预期进行;但是, nodent
- 一个不同的转换 - 打印 TypeError:three.then不是函数
。这是正确的,为什么?
Default babel.js transformation logs 5 as expected; however, nodent
- a different transform - prints TypeError: three.then is not a function
. Which is correct and why?
推荐答案
根据当前工作草案规范,运行时应首先将等待值转换为承诺:
According to the current working draft spec, the runtime should "cast" the awaited value to a promise first:
AsyncFunctionAwait( value )
AsyncFunctionAwait ( value )
- 让
asyncContext
成为正在运行的执行上下文。 - 让
promiseCapability
为! NewPromiseCapability(%Promise%)
。 - 让
resolveResult
成为!调用(promiseCapability。[[Resolve]],undefined,value)
。 - ...
- Let
asyncContext
be the running execution context. - Let
promiseCapability
be! NewPromiseCapability(%Promise%)
. - Let
resolveResult
be! Call(promiseCapability.[[Resolve]], undefined, value)
. - ...
步骤2和3的组合大致相当于调用 Promise.resolve(value)
,它创建一个使用给定值解析的新promise或 - 如果值是一个很好的 - 将跟随那个。
Step 2 and 3 combined is roughly equivalent to calling Promise.resolve(value)
, which creates a new promise that is resolved with the given value or - if the value is a thenable - will follow that thenable.
换句话说: await 3
相当于等待Promise.resolve(3)
,并且Babel正确实现了规范。
In other words: await 3
is equivalent to await Promise.resolve(3)
, and Babel implements the spec correctly.
nodent另一方面故意不支持默认等待非承诺。如果您希望所有等待的值首先包含在promise中,则可以使用 wrapAwait
选项,但nodent文档报告这可能会影响性能。
nodent on the other hand deliberately does not support awaiting a non-promise by default. There's a wrapAwait
option available if you want all awaited values to be wrapped in a promise first, but the nodent documentation reports that this may affect performance.
这篇关于当关键字后面的表达式没有评估为承诺时,`await`会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!