search

Home  >  Q&A  >  body text

How to use await with non-async functions

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?

某草草某草草2752 days ago707

reply all(3)I'll reply

  • 为情所困

    为情所困2017-05-16 13:35:34

    async does not require await, await must rely on async

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 13:35:34

    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(...)
    }

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 13:35:34

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

    reply
    0
  • Cancelreply