我对目前关于将async函数和关键字添加await到下一个EcmaScript的讨论感到困惑.
我不明白为什么有必要在async关键字之前使用function关键字.
从我的观点来看,await关键字等待发电机或承诺的结果做一个函数的return应该是足够的.
await应该在普通函数和生成器函数中简单可用,无需额外的async标记.
如果我需要创建一个函数作为结果应该可用await,我只需使用一个promise.
我的理由是这个很好的解释,下面的例子来自:
async function setupNewUser(name) {
var invitations,
newUser = await createUser(name),
friends = await getFacebookFriends(name);
if (friends) {
invitations = await inviteFacebookFriends(friends);
}
// some more logic
}
Run Code Online (Sandbox Code Playgroud)
它也可以作为普通函数完成,如果函数的执行将等待完成孔函数,直到满足所有等待.
function setupNewUser(name) {
var invitations,
newUser = await createUser(name),
friends = await getFacebookFriends(name);
if (friends) {
invitations = await inviteFacebookFriends(friends);
}
// return because createUser() and getFacebookFriends() …Run Code Online (Sandbox Code Playgroud) 必须在包含函数上使用async关键字才能在函数体内使用await。
async function fetchMovies() {
const response = await fetch('/movies');
console.log(response);
}
fetchMovies();
Run Code Online (Sandbox Code Playgroud)
在AWAIT被用来对异步完成方框取()调用。从代码中可以看出,函数fetchMovies()甚至没有返回任何值。即使这样做了,它也会影响调用者使用返回值的方式,但是为什么它会影响从函数体调用另一个异步调用呢?
我的问题是为什么需要这样做?有什么好的解释吗?它是否与实际实现await的需要有关,并在旧的 JavaScript 版本中支持它?
我知道使用了iffi模式能够使用await但这是否会以任何方式更改iffi代码块后面的代码的语义?
(async () => {
const response = await fetch('/movies');
console.log(response);
})();
Run Code Online (Sandbox Code Playgroud)
我也知道模块中支持顶级等待。
可能是我错过了一些非常明显的东西。