猿问

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

元芳怎么了
浏览 985回答 1
1回答

繁星coding

async 可以不需要 await, await 必须依赖 async
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答