Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 113 期(W3C 标准-JavaScript-异步):async 和 await #116

Open
wingmeng opened this issue Sep 20, 2019 · 0 comments
Open

第 113 期(W3C 标准-JavaScript-异步):async 和 await #116

wingmeng opened this issue Sep 20, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

对于异步编程,使用 Promise 是一种非常棒的实践,利用 then 方法的链式调用,可以让我们的代码清晰明了,但链式调用是串行的,如果编程中需要并行处理怎么办?例如我们有多个异步事件,它们之间并无联系而且没有先后顺序,但需要全部完成才可以进行下一步工作。你可能会说可以用 Promise.all,这的确是一种解决方式,这里推荐更棒的一种方式是 async/await 方法。

async/await 是基于 Promise 的语法糖,可以让我们以同步代码的组织形式来完成异步编程。

注意:当一个函数声明为 async 时,内部可以没有 await,但一个内部包含 await 方法的函数,一定得是 async 函数。

async function timeout(seconds) {
  if (seconds > 0) {
    let result = await new Promise(resolve => {
      setTimeout(() => {
        console.log(`await 代码执行完毕`);
        resolve(`hello world`);
      }, seconds * 1e3);
    });
    console.log(`我是 await 后面的代码`);
    return result;
  } else {
    throw `TypeError: \`seconds\` should be a number, and more than zero`;
  }
}

timeout(1).then(res => console.log(`输出结果:`, res));
console.log(`虽然在后面,但我先执行`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant