How to use await with non-async functions
某草草
某草草 2017-05-16 13:33:34
0
3
634

await needs to be used in an async function, so every time we want to use await, we must first define it in the async function and then call this async function.

Just like this

async function fn(){}
fn()

A more detailed example

        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);

Every time you use await, you need to define async one more time and then call it. I find this process a little troublesome and repetitive, so I would like to ask if there is any way to optimize or solve this problem?

某草草
某草草

reply all(3)
为情所困

async does not require await, await must rely on async

左手右手慢动作

The return value of the function declared by async is a Promise object:

Such a function

async function fn() {}

To use await, you need to put it in the async function

async function anthor() {
    await fn()
}

If you don’t use await, just use it as Promise

function anthor() {
    fn().then(...).catch(...)
}
滿天的星座

Try this

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!