欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > 前端(async 和await)

前端(async 和await)

2025/5/2 11:44:30 来源:https://blog.csdn.net/m0_67244960/article/details/144455300  浏览:    关键词:前端(async 和await)

1 async

async 将 function 变为成为 async 函数

●async 内部可以使用 await,也可以不使用,因此执行这个函数时,可以使用 then 和 catch 方法

●async 函数的返回值是一个 Promise 对象

●Promise 对象的结果由 async 函数执行的返回值决定

async function funcName() {
​
•    //statements 
​
}

○函数体不 return 返回值,则 async 函数返回值为一个成功 fulfilled 的 Promise 对象,值为 undefined

let a = async function() {}
​
let res = a()
​
console.log(res) // Promise{<fullfilled>: undefined}

○return 结果不是一个 Promise ,则 async 函数返回值为一个成功 fulfilled 的 Promise 对象,状态值为这个内部返回值

let a = async function () {
​return 'hello'
​
}
​
let res = a()
​
console.log(res) // Promise{<fullfilled>: 'hello'}

○内部抛出错误,则 async 函数返回值为一个失败 reject 的 Promise 对象

let a = async function foo() {
​throw new Error('出错了')
​
}
​
a().then(()=>{console.log("ok");},()=>{console.log("error");}) //456

2 await await 相当于一个运算符,右边接一个值。一般为一个 Promise 对象,也可以是一个非 Promise 类型。 ●当右接一个非 promise 类型,await 表达式返回的值就是这个值;当右接一个 promise 对象,则 await 表达式会阻塞后面的代码,等待当前 promise 对象 resolve 的值 综合 async 和 await 而言 ●await 必须写在 async 函数中 ●await 右侧的表达式一般为 promise 对象 ●await 返回的是 promise 成功的值

 async function f1(){console.log(1);let x = await Promise.resolve("2")console.log("x:"+x);
​}let res = f1();console.log(res);

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词