相关疑难解决方法(0)

ES2017 - 异步与收益率

我对目前关于将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)

javascript async-await ecmascript-6 ecmascript-2017

32
推荐指数
3
解决办法
7252
查看次数