当前位置:网站首页>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的帮助!
希望对你有帮助!
如有错误,欢迎指正!
*/
边栏推荐
- ArrayList collection, object array
- [piecemeal knowledge] [network composition] the mobile phone can be connected to the campus network, but the computer can't
- SISO decoder for a general (n,n-1) SPC code(补充章节3)
- 6-2 writing articles (*)
- Learning about canvas API
- [solution] codeforces round 798 (Div. 2)
- Global and Chinese markets of solid polymer aluminum capacitors 2022-2028: Research Report on technology, participants, trends, market size and share
- 网络安全威胁情报体系
- Système d'information sur les menaces à la sécurité des réseaux
- Intelligent overall legend, legend of wiring, security, radio conference, television, building, fire protection and electrical diagram [transferred from wechat official account weak current classroom]
猜你喜欢

SISO Decoder for min-sum(补充章节2)

mysql8安装,navicat安装,sqli-labs搭建

Hello go (XV). Go language common standard library V

ACL 2022:评估单词多义性不再困扰?一种新的基准“DIBIMT”
![[collect first and use it sooner or later] 100 Flink high-frequency interview questions series (I)](/img/3e/efce1cff81abf395ffc24ac57b05d7.png)
[collect first and use it sooner or later] 100 Flink high-frequency interview questions series (I)

Getting started with Wireshark

SISO Decoder for a General (n, N - 1) SPC Code (Supplementary section 3)

SISO Decoder for Repetition(补充章节4)

Upload labs failed to pass the customs halfway and the middle road collapsed

【C】 Compilation preprocessing and environment
随机推荐
av_ read_ The return value of frame is -5 input/output error
SISO Decoder for a General (n, N - 1) SPC Code (Supplementary section 3)
Intelligent overall legend, legend of wiring, security, radio conference, television, building, fire protection and electrical diagram [transferred from wechat official account weak current classroom]
Upload labs failed to pass the customs halfway and the middle road collapsed
RadioGroup动态添加RadioButton
【MapReduce】一个完整MR程序案例教你如何用IDEA打包及运行
SISO decoder for min sum (supplementary Chapter 2)
Network Security Threat Intelligence System
The top ten trends of 2022 industrial Internet security was officially released
Three steps of ffmpeg CBR precise bitstream control
Ctfhub SQL Boolean blind annotation
LeetCode_ Prefix tree_ Medium_ 208. implement trie (prefix tree)
ISCSI详解(四)——ISCSI服务端配置实战
送给大模型的「高考」卷:442人联名论文给大模型提出204个任务,谷歌领衔
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
Using packstack to quickly install openstack
Simple understanding of events
SISO Decoder for Repetition(补充章节4)
【先收藏,早晚用得到】100个Flink高频面试题系列(一)
Jsfinder, wafw00f installation, nmap configuration (msvcr120.dll file is missing)