javascript - 如何在非async函数下使用await
某草草
某草草 2017-05-16 13:33:34
[Node.js讨论组]

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

某草草
某草草

全部回复(3)
为情所困

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

ringa_lee

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);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号