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

async 和 await 的原理 #5

Open
chenhuiYj opened this issue May 29, 2020 · 0 comments
Open

async 和 await 的原理 #5

chenhuiYj opened this issue May 29, 2020 · 0 comments

Comments

@chenhuiYj
Copy link
Owner

chenhuiYj commented May 29, 2020

概念

字面意思来理解。async 是“异步”的意思,await 可以认为是 async wait 的简写。就是用 async 来申明一个异步 function 的,而 await 用于等待一个异步方法执行完成。所以在写 await 的时候,里面的函数必须是异步的函数,就是 function 必须要用 async 声明。

async 和 await 用了同步的方式去做异步,async 定义的函数的返回值都是 promise,await 后面的函数会先执行一遍,然后就会跳出整个 async 函数来执行后面js栈的代码

注意点

1.await 命令后面的 Promise 对象,运行结果可能是 rejected,所以最好把 await 命令放在 try...catch 代码块中

async function myFunction() {
  try {
    await somethingThatReturnsAPromise();
  } catch (err) {
    console.log(err);
  }
}

// 另一种写法

async function myFunction() {
  await somethingThatReturnsAPromise().catch(function (err){
    console.log(err);
  });
}
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