多个异步请求,如何按顺序加载?

是UNIAPP里的函数加载顺序。

onLoad: function(option) {
            this.draftId = option.draftId;
            this.getSurveyorList();
            this.getDictPortBerth();
            this.getDictCargoName();
            this.getTaskInfo(taskId);
            // 判断如果有taskId,则是编辑页面
            let taskId = option.taskid;
            if (taskId) {
                this.isEdit = true; //设置是编辑页面
                this.getTaskInfo(taskId);
                uni.setNavigationBarTitle({
                    title: '修改测量任务'
                });
            }
        },

this.getSurveyorList();
this.getDictPortBerth();
this.getDictCargoName();
this.getTaskInfo(taskId);

这四个方法都是异步请求的,前三个是获取数据字典的数据。
目前同时执行的话,有时候因为速度不一致,偶尔会导致拿不到字典数据。
如何让这四个函数/方法,按上下顺序执行?应该使用Promise,但是没研究明白。

这是其中一个方法的写法:

//获取字典数据-泊位
            async getDictPortBerth() {
                const res = await this.$myRequest({
                    url: 'system/dict/data/type/draft_port_berth'
                })
                this.berth = res.data.data.map(item => item.dictValue) //es6二维数组取值,形成新的一位数组
            }
阅读 3.9k
2 个回答

既然你的开发环境支持 async function,直接全加上 await 就好了:

await this.getSurveyorList();
await this.getDictPortBerth();
await this.getDictCargoName();
await this.getTaskInfo(taskId);

如果前三个没有顺序要求,只有第四个要等前三个完成,那就:

await Promise.all([
    this.getSurveyorList(),
    this.getDictPortBerth(),
    this.getDictCargoName(),
]);
await this.getTaskInfo(taskId);

Promise.all(),可以了解一下

let fun1 = () => {return new Promise(...)};
let fun2 = () => {return new Promise(...)};
let fun = () => {
Promise.all([fun1, fun2]).then((res) => {
// res 是个数组 可以自己打印看看
}).catch(err => {
// 错误回调
});
}

fun();

大概是这么个意思~

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进