当关键字后面的表达式没有评估为承诺时,`await`会发生什么? [英] What should happen with `await` when the expression after the keyword does not evaluate to promise?

查看:85
本文介绍了当关键字后面的表达式没有评估为承诺时,`await`会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的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 )


  1. asyncContext 成为正在运行的执行上下文。

  2. promiseCapability ! NewPromiseCapability(%Promise%)

  3. resolveResult 成为!调用(promiseCapability。[[Resolve]],undefined,value)

  4. ...

  1. Let asyncContext be the running execution context.
  2. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  3. Let resolveResult be ! Call(promiseCapability.[[Resolve]], undefined, value).
  4. ...


步骤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屋!

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