javascript - 如何在非async函数下使用await
问题描述
await需要在async函数中使用,所以每次我们想要使用await必须先在async函数中定义,然后调用这个async函数。
就比如这样
async function fn(){}fn()
详细一点的例子
async function asy(){ // 获取当前城市的位置 获取热门城市 获取所有城市 const [resCityGuess,resCityHot,resCityAll]=await Promise.all([ this.http.get(’api/v1/cities?type=guess’), this.http.get(’api/v1/cities?type=hot’), this.http.get(’api/v1/cities?type=group’) ]) this.cityGuessName=resCityGuess.data.name; this.cityGuessId=resCityGuess.data.id; this.cityHot=resCityHot.data; this.cityAll=resCityAll.data;}asy.apply(this);
每次使用await之前都需要多定义一次async然后再调用,这一个过程我觉得略微麻烦以及重复,所以想问下是否存在什么办法优化或者解决这一问题?
问题解答
回答1:async 可以不需要 await, await 必须依赖 async
回答2:async声明的函数返回值是Promise对象:
这样一个函数
async function fn() {}
使用await就需要放在async函数中
async function anthor() { await fn()}
不使用await就当作Promise用
function anthor() { fn().then(...).catch(...)}回答3:
试试这样
function asy(){ // 获取当前城市的位置 获取热门城市 获取所有城市 Promise.all([this.http.get(’api/v1/cities?type=guess’),this.http.get(’api/v1/cities?type=hot’),this.http.get(’api/v1/cities?type=group’) ]).then(values =>{this.cityGuessName=resCityGuess.data.name;this.cityGuessId=values[0].data.id;this.cityHot=values[1].data;this.cityAll=values[2].data; });}asy.apply(this);
相关文章:
1. mysql - 一个sql的问题2. mysql插入文本如果是个sql语句就报错了3. javascript - 使用vue-cli有个报错ERR_INCOMPLETE_CHUNKED_ENCODING4. linux - python 安装 Anaconda 环境变量问题请教5. mysql - SQL添加记录的数据来源于同一个表6. html5 - 请问一下写H5的时候 你们都是兼容那些手机7. python3.x - python多线程如何修改数据?8. mysql连表排序9. css3 - 没明白盒子的height随width的变化这段css是怎样实现的?10. mysql sql where id in(25,12,87) 结果集如何用按照 25 12 87排序?

网公网安备