javascript - 异步/等待 native 实现

标签 javascript async-await ecmascript-2017

This proposal建议 async 函数可以在幕后使用生成器函数,尽管我在 ES2017 规范中找不到对此的确认。

此外,当生成器原型(prototype)在 Chrome/Node.js 中变得困惑时,async 函数似乎没有受到影响,这表明未使用 GeneratorFunction通过 AsyncFunction,至少直接:

Object.getPrototypeOf((function * () {}).prototype).next = null;

(async () => {
    return await Promise.resolve(1);
})()
.then(console.log);

async/await 在现有的原生实现中到底是如何工作的?

这些实现是否比提案建议的通常在 Babel 和 TypeScript 中实现的 Promise/generator 函数方法更高效?

最佳答案

How exactly does async/await work in existing native implementations?

如果我们查看实际的 native implementation of async await in v8,我们可以清楚地看到 promise 和生成器都是异步等待实现的明显基础,同样在 parser 中它清楚地说明了异步等待脱糖的生成器 promise 性质。

关于 ES 规范,即使规范没有直接提及执行上下文切换的实际实现,它暗示了 Perform ! Call(promiseCapability.[[Resolve]] 正在使用的相同 Promise.resolve 机制的用法。因此主观上暗示可能的“机制”来处理 asyncContext 的运行执行上下文切换。

Moreover, when generator prototype becomes messed up in Chrome/Node.js, async functions don't seem to be affected, this suggests that GeneratorFunction isn't used by AsyncFunction, at least directly:

运行时中的 generatorasync 函数都是 Function 对象的后代,但它们并不相互继承,这就是为什么您看不到已提交的更改的原因。

但是特定宿主对象或方法的实际 native 级实现不一定与已编译对象及其依赖项的运行时执行相关联,就像您不能通过重新分配 Function.prototype.call = () => {} 来改变函数的调用能力一样,因为 %call% 是原生级别的实现。

Are the implementations more performant than it would be possible with Promise/generator function approach that is suggested by the proposal and is usually implemented in Babel and TypeScript?

它依赖于 js 引擎及其实现的编译级优化和反优化,但它会不断变化,有时 native 实现比 3rd 方库实现慢,如 it happened with es5 map, forEach vs lodash counterparts ,但在大多数情况下, native 级实现是无与伦比的,因为更接近机器代码。这里的例子是 2x prevalence of async-await in jsbench with async-await vs babel regenerator vs promise

关于javascript - 异步/等待 native 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908575/

相关文章:

javascript - ToggleClass 动画 jQuery?

javascript - 在变量上存储 jquery 函数

javascript - self 更新时更新 ng-repeat 中的模型

typescript - 以 Safari 为目标时,如何在 TypeScript (angular2) 中使用 await/async?

c# - 异步编程和多线程有什么区别?

javascript - 如何在 map 中正确使用 async 和 await 关键字

javascript - 将二维数组转换为对象的好方法

javascript - 正则表达式 : match either of two conditions?

c# - ASP.NET 中的异步 JSON 反序列化

javascript - js async/await 在使用此关键字时抛出错误