如何在非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然后再调用,这一个过程我觉得略微麻烦以及重复,所以想问下是否存在什么办法优化或者解决这一问题?

阅读 7.3k
3 个回答

async 可以不需要 await, await 必须依赖 async

async声明的函数返回值是Promise对象:

这样一个函数

async function fn() {}

使用await就需要放在async函数中

async function anthor() {
    await fn()
}

不使用await就当作Promise用

function anthor() {
    fn().then(...).catch(...)
}

试试这样

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);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题