曾志强*_*曾志强 10 html javascript asynchronous ecmascript-2017
等待是es7的一个惊人功能.
但是,每当我使用await时,我发现我必须定义一个异步函数并调用此函数.
如
async function asy(){
const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
this.http.get('api/v1/cities?type=guess'),
this.http.get('api/v1/cities?type=hot'),
this.http.get('api/v1/cities?type=group')
])
this.cityGuessName=resCityGuess.data.name;
this.cityGuessId=resCityGuess.data.id;
this.cityHot=resCityHot.data;
this.cityAll=resCityAll.data;
}
asy.apply(this);
Run Code Online (Sandbox Code Playgroud)
我想要的是使用等待没有异步功能,如
// the async function definition is deleted
const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
this.http.get('api/v1/cities?type=guess'),
this.http.get('api/v1/cities?type=hot'),
this.http.get('api/v1/cities?type=group')
])
this.cityGuessName=resCityGuess.data.name;
this.cityGuessId=resCityGuess.data.id;
this.cityHot=resCityHot.data;
this.cityAll=resCityAll.data;
// without call fn
Run Code Online (Sandbox Code Playgroud)
我想定义函数fn并调用此fn有时会重复,所以我想知道是否可以优化这种情况?
我可以使用await而不是异步吗?
非常感谢!
Poi*_*nty 14
不.await操作员只在async功能中有意义.
编辑 - 详细说明:整体async和await交易可以被认为像LISP宏.什么语法确实是告知发生了什么事情的语言解释系统,使之能有效合成周围代码的转化为回调请求的基础无极序列.
因此,使用语法是编写显式Promise内容的隐式快捷方式,通过调用.then()等等.运行时必须知道函数是async因为它知道async函数内部的表达式需要转换为通过a返回Promises发电机构.并且,由于重叠的原因,async函数声明上的装饰告诉语言这实际上是一个返回Promise的函数,它需要处理它.
所以,它很复杂.改进和扩展JavaScript的过程必须考虑到世界上存在难以想象的大量JavaScript代码的事实,因此几乎在所有情况下,没有任何新功能可以导致自2002年以来未触及的页面失败.
不完全没有,async但看一下,这可能会说明问题。
您可以有效地创建箭头函数(有意匿名)。
箭头函数是用于编写匿名函数的 ECMAScript2015 语法。它们具有许多与 JavaScript 中原始 function 关键字不同的功能,但在许多情况下它们可以直接替代匿名函数。
添加async关键字,用括号将函数括起来,并添加另一个括号来运行该函数。
在函数内部,使用await关键字。
像这样:
(async () => {
console.log("Message in 5s");
await new Promise((resolve) => setTimeout(() => resolve(), 5000));
console.log("If you like it, show it");
})();
Run Code Online (Sandbox Code Playgroud)
它被提议给 ECMAScript。
Chrome/Chromium(以及任何具有最新的基于 V8 的 JS 引擎)都有一个似乎符合规范的工作实现。
提案本身处于第 3 阶段。
更多信息:
https://github.com/tc39/proposal-top-level-await
https://v8.dev/features/top-level-await