前端前端

JS 中的 async/await

2020-09-23  本文已影响0人  limengzhe

async/await 是什么?

如何使用?

const pm = function () {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("pm");
      resolve("ok");
    }, 2000);
  });
};

async function aa() {
  await pm().then(res => {
    console.log(res);
  });
  // 接下来要被执行的代码
  console.log(`aa`);
}

aa();
pm // 2000ms later
ok
aa
const pm = function () {
  return new Promise((resolve, reject) => {
    console.log("pm");
    reject();
  });
};

async function aa() {
  try {
    await pm().then(res => {
      console.log(res);
    });
  } catch {
    console.log(`aa`);
  }
}

aa();
pm
aa
上一篇 下一篇

猜你喜欢

热点阅读