1.async

  • 返回值是一个promise对象
1
2
3
4
let result = async () => {
return 21;
};
console.log(result());

2.await

  • 右侧表达式为promise对象,但也可以是其他的值
  • 表达式为promise对象则为成功的值
  • 其他值,则直接将此值作为await的返回值

注意

1.await必须写在async函数中,但async函数可以没有await

2.await的promise对象失败了,则会抛出异常,需要通过try catch进行捕获

1
2
3
4
5
6
7
8
let result = async () => {
let p = new Promise((resolve, rejsct) => {
resolve("ok");
});
let res = await p;
console.log(res);
};
result();

3.结合实践

1
2
3
4
btn.addEventListener("click", async function() {
let duanzi = await sendAJAX("https://api.apiopen.top/getJoke");
console.log(duanzi);
});