Skip to main content

async 和 await

async

  • async 关键字用来修饰函数 被他修饰的函数 返回的一定是个 Promise
  • 如果函数中返回的是一个值 async 直接会用 Promise.resolve()包裹返回
async function method1() {
return 1;
}

method1();
//Promise<fufilled> { 1 }

await

  • await 表示某一个 Promise 完成 必须要写在 async 修饰的函数里面
  • Promise 抛出的错误 需要用到 try-catch{} 捕获
function delay(duration) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, duration);
});
}

const test = async () => {
try {
await delay(2000);
} catch (e) {
console.log(e);
}
};
//Promise<fufilled> { 1 }
  • await 后面的代码相当于进入到了微队列里面
const m = async () => {
const n = await 1;
console.log(n);
};

m();
console.log(2);

// 相当于;
const m = () => {
return Promise.resolve(1).then((n) => {
console.log(n);
});
};
console.log(2);