Async / Await

这是一个语言层面的异步编程标准
这个语法糖没有什么值得深究的东西

// Async / Await 语法糖

function ajax(url) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.responseType = "json";
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(new Error(xhr.statusText));
      }
    };
    xhr.send();
  });
}

async function main() {
  try {
    const users = await ajax("/api/users.json");
    console.log(users);

    const posts = await ajax("/api/posts.json");
    console.log(posts);

    const urls = await ajax("/api/urls.json");
    console.log(urls);
  } catch (e) {
    console.log(e);
  }
}

const promise = main();

promise.then(() => {
  console.log("all completed");
});

await的语法要在被async声明的函数中才可以调用
不需要async的await调用写法正在开发中,不久的将来就可以使用了

最后修改:2023 年 06 月 06 日
收款不要了,给孩子补充点点赞数吧