当前位置:网站首页>async导致函数结果出乎意料,改变原来代码的意图;await is only valid in async functions and the top level bodies of modules
async导致函数结果出乎意料,改变原来代码的意图;await is only valid in async functions and the top level bodies of modules
2022-06-11 17:57:00 【琹箐】
目录
一、问题
1.有个需求:需要在原有的函数中调用一个接口后,根据接口的值返回 Boolean值。为了正确获取接口调用的值,在原有的函数上添加了 async,并且在接口调用时使用了 await接收。结果居然把原来的代码都改出问题了,注释了自己添加的代码后,仍然有问题;全部撤销后没有问题,还一直以为是自己添加的代码注释后 仍然被调用了,经过仔细排查后才发现是 因为 添加了 async 这个标识,整个函数的返回值不再是一个简单的 Boolean值,看上去是,其实上返回的是一个 promise。所以原来 的判断逻辑,全都变成了 true.
//伪代码
let originfunction=async()=>{
//调用接口判断
let result= await this.getIsChange();
console.log("result",result);
if(result){
return true;
}
//原来的逻辑
//有返回true,也有返回false的情况
},
getIsChange(){
_xxx()
.then((result)=>{
if(result.status===200){
return result.ischange;
}
})
.catch((error)=>{
console].log("error",error);
)
二、解决方法
1.下面用一个实际说明,运行结果如 图2-1所示:async函数返回的都是 promise,需要使用 await来接收解析 promise
例如下面的返回值 result看起来 special为false时,会直接返回 result:100,但是不用await接收返回的就是一个promise
1)使用await时,必须写在async函数中,否则会报错:Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
2)使用async不一定需要await,但是一定注意:async函数的返回值不再是一般的数据类型,而是promise类型,所以需要用 await解析后再接收
let add = async (a, b) => {
return a + b;
}
let asyncShow = async (special) => {
let span_result = document.getElementById("result");
let result = 100;
if (special) {
result = await add(3, 4)
span_result.innerText = result;
}
span_result.innerText = result;
return result;
}
window.onload=async () => {
// async方法返回的东西 必须用await接收,否则收到的就是一个promise,需要自己解析
let result = asyncShow();
// result Promise {<fulfilled>: 100}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: 100
console.log("result", result)
let awaitResult = await asyncShow();
//awaitResult 100
console.log("awaitResult", awaitResult);
let specailResult=asyncShow(true);
// specialResult Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: 7
console.log("specialResult",specailResult);
let awaitSpecialResult=await asyncShow(true);
// awaitSpecialResult 7
console.log("awaitSpecialResult",awaitSpecialResult)
}
// 使用await时,必须写在async函数中,否则会报错:Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at async.js:25:19)
// let awaitResult = await asyncShow();
// console.log("awaitResult", awaitResult);
// 使用async不一定需要await,但是一定注意:async函数的返回值不再是一般的数据类型,而是promise类型,所以需要用 await解析后再接收

三、总结
1.async函数返回的是一个promise,需要使用 await接收。
2.await必须写在 async函数中。
/*
感谢wxy的帮助!
希望对你有帮助!
如有错误,欢迎指正!
*/
边栏推荐
- 了解一下random库·1
- 夜神安装apk,以及bp代理
- SQL语句当查询条件为空时默认查询全部数据,不为空是则按照条件进行查询
- SISO Decoder for a General (n, N - 1) SPC Code (Supplementary section 3)
- Rtsp/onvif protocol easynvr video platform arm version cross compilation process and common error handling
- Initial egg framework
- [collect first and use it sooner or later] 49 Flink high-frequency interview questions series (I)
- SQL statement when the query condition is blank, all data will be queried by default. If it is not blank, the query will be performed according to the condition
- After class, I looked at the document and went back to the lab. I picked up the forgotten SQL operators again
- Three steps of ffmpeg CBR precise bitstream control
猜你喜欢
![[collect first and use it sooner or later] 100 Flink high-frequency interview questions series (II)](/img/cf/44b3983dd5d5f7b92d90d918215908.png)
[collect first and use it sooner or later] 100 Flink high-frequency interview questions series (II)

神经网络与深度学习-2- 机器学习简单示例-PyTorch

送给大模型的「高考」卷:442人联名论文给大模型提出204个任务,谷歌领衔

After class, I looked at the document and went back to the lab. I picked up the forgotten SQL operators again
![[foundation of deep learning] learning of neural network (3)](/img/a5/1b80ba85faf8fa636b784c76d4df2f.png)
[foundation of deep learning] learning of neural network (3)

Radiogroup dynamically add RadioButton

Common shortcut keys for Hello go (x) and GoLand

Tle6389-2g V50's unique pwm/pfm control scheme has a duty cycle of up to 100%, forming a very low differential pressure - keshijin mall

【C】 Compilation preprocessing and environment
![Codeworks round 479 (Div. 3) [done]](/img/a0/f3c6989d8f755c03076b237514ee64.jpg)
Codeworks round 479 (Div. 3) [done]
随机推荐
Database lock and transaction isolation level
Explain AI accelerators in detail: GPU, DPU, IPU, TPU... There are infinite possibilities for AI acceleration schemes
Chorus translation
密评-----
Tle6288r is a 6-channel (150 MOhm) intelligent multi-channel switch using intelligent power technology - keshijin mall
SISO decoder for min sum (supplementary Chapter 2)
【新手上路常见问答】关于项目管理
7-2 h0107. Pig-Latin
Intelligent overall legend, legend of wiring, security, radio conference, television, building, fire protection and electrical diagram [transferred from wechat official account weak current classroom]
[collect first and use it sooner or later] 49 Flink high-frequency interview questions series (II)
【先收藏,早晚用得到】49个Flink高频面试题系列(一)
Cryptology Summary
Network Security Threat Intelligence System
Winter vacation daily question 2022 [week1 not finished]
PIL-Pillow图像处理【1】-安装与新建
6-6 batch sum (*)
upload-labs通关未半而中道崩殂
How ZABBIX can customize MySQL monitoring items and trigger alarms
About element location and size
Hello go (XV). Go language common standard library V