Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

对于异步编程,使用 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(`虽然在后面,但我先执行`);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.