发布时间:2025-12-10 11:27:39 浏览次数:7
async函数体里没有搭配await关键字使用时,async函数的执行和普通函数一致
async function fn1() {console.log("我是async异步函数");}function fn2() {console.log("我是普通函数");}fn1()fn2()控制台执行:
async函数体里搭配await关键字使用时,async函数体执行遇到await关键字时,await会阻塞async函数体继续往下执行,await往下的代码会被进入异步任务队列中等待主线程执行完毕后再执行
案例1:
控制台执行:
案例2:
控制台执行:
async函数的返回值全为Promise对象:
执行:
执行:
执行:
执行:
执行:
注意:await运算符一定要在async函数里使用,一般我们使用await + promise对象搭配使用,获取promise对象为成功的结果值
案例:
async function fn() {// let result = await 1// let result = await 1 + 1// let result = await 'hsq'// let result = await function () {// console.log('函数');// }// let result = await [1, 2, 3]let result = await {name: 'hsq'}console.log(result);}fn()执行:
await + promise对象运行结果返回promise对象状态为成功的的结果值
案例:
②peomise对象为等待
async function fn() {let result = await new Promise((reslove, reject) => {})console.log(result);}fn()执行:
ps: promise对象为等待时,await + promise对象运行结果无法获取结果
②peomise对象为失败
async function fn() {let result = await new Promise((reslove, reject) => {setTimeout(() => {reject("失败")}, 1000)})// .catch(res => {// console.log(res);// })console.log(result);}fn()执行:
ps:当promise对象为失败时,线程会抛出异常, await + promise对象运行结果无法返回promise对象状态为失败的的结果值,可以通过promise的.catch()方法获取promise失败的结果值
③peomise对象为成功
async function fn() {let result = await new Promise((reslove, reject) => {setTimeout(() => {reslove("成功获取的数据")}, 1000)})console.log(result);}fn()执行:
案例:
async function getData() {return new Promise((reslove, reject) => {setTimeout(() => { reslove("成功获取后端返回数据") }, 1000)})}async function useData() {let result = await getData()console.log(result);}useData()执行:
1、async表示异步,async函数执行时遇到await只会阻塞自己函数体内代码的执行,不会阻塞主线程代码的执行,所以称为异步函数
2、await只能存在在async异步函数中,我们一般使用async+await+promise进行异步编程,await+promise只能获取promise对象为成功时的结果值,promise对象为失败时的结果值只能通过捕获异常的方式获取。