在 uni-app 中 uni.request 默认是异步请求,那么如果我们想将其改为同步请求可以吗?显然是可以的!我们可以借助 Promise 结合 async + await 使请求同步化。具体步骤如下:

基于 Promise 对 request 请求进行封装

请参考之前的文章:uni-app 基于 Promise 的 request 请求封装

使用 async + await,使异步请求同步化

<script>
    import http from '@/commons/http.js'

    export default {
        data() {
            return {
            }
        },
        methods: {
            async loadData1 (id) {
                await http('data/get1', {
                    id: id
                }).then(res => {
                    console.log(res.data)
                }).catch(err => {
                    console.error(err)
                })
            },
            async loadData2 (id) {
                await http('data/get2', {
                    id: id
                }).then(res => {
                    console.log(res.data)
                }).catch(err => {
                    console.error(err)
                })
            }
        },
        async onLoad(option) {
            await this.loadData1(1)
            await this.loadData1(2)
        }
    }
</script>

注意:当调用的级数增加的时候,需要逐级的增加 async 和 await。

如果觉得我的文章对你有用,请点个赞