javascript面试题:什么是 async/await 及其如何工作?

2020-01-1623:15:46WEB前端开发Comments4,320 views字数 1253阅读模式

51. 什么是 async/await 及其如何工作?

async/await是 JS 中编写异步或非阻塞代码的新方法。它建立在Promises之上,让异步代码的可读性和简洁度都更高。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

async/await是 JS 中编写异步或非阻塞代码的新方法。 它建立在Promises之上,相对于 Promise 和回调,它的可读性和简洁度都更高。 但是,在使用此功能之前,我们必须先学习Promises的基础知识,因为正如我之前所说,它是基于Promise构建的,这意味着幕后使用仍然是Promise文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

使用 Promise文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

function callApi() {
  return fetch("url/to/api/endpoint")
    .then(resp => resp.json())
    .then(data => {
      //do something with "data"
    }).catch(err => {
      //do something with "err"
    });
}
复制代码

使用async/await文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

async/await,我们使用 tru/catch 语法来捕获异常。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

async function callApi() {
  try {
    const resp = await fetch("url/to/api/endpoint");
    const data = await resp.json();
    //do something with "data"
  } catch (e) {
    //do something with "err"
  }
}
复制代码

注意:使用 async关键声明函数会隐式返回一个Promise文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

const giveMeOne = async () => 1;

giveMeOne()
  .then((num) => {
    console.log(num); // logs 1
  });
复制代码

注意:await关键字只能在async function中使用。在任何非async function的函数中使用await关键字都会抛出错误。await关键字在执行下一行代码之前等待右侧表达式(可能是一个Promise)返回。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

const giveMeOne = async () => 1;

function getOne() {
  try {
    const num = await giveMeOne();
    console.log(num);
  } catch (e) {
    console.log(e);
  }
}

// Uncaught SyntaxError: await is only valid in async function

async function getTwo() {
  try {
    const num1 = await giveMeOne(); // 这行会等待右侧表达式执行完成
    const num2 = await giveMeOne(); 
    return num1 + num2;
  } catch (e) {
    console.log(e);
  }
}

await getTwo(); // 2

作者:前端小智
链接:https://juejin.im/post/5e1faa3d51882520a167df0e
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/17741.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/17741.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定