解决先异步调用一个接口,再根据返回值继续循环异步,然后再同步的场景.then的连续调用

发布时间 2023-12-21 14:44:24作者: 影思密达ing

场景描述:人员select下拉框为分页只查20个数据下拉(真实数据可能下拉有大几千),但是编辑页进来的id不在这20个数据下拉之内,所以显示的就是id值数组(因为是多选下拉框)

解决:编辑回显方法内写

getUserSecList(data.collaboratorVoList);

然后先调人员20个下拉,调完后,根据传参的编辑id进行循环遍历,判断是不是在这个20个下拉里面,如果不在则给cyList里面追加

坑点,会存在同步异步的大bug,因为先异步调getUserlistInter,然后在这成功回调里面需要先进行人员遍历,不在的在异步调根据id查人员的接口,然后再进行

postForm.collaboratorList = ownerId?.map((item: any) => item.collaborator);

编辑回显,只能用.then().then()进行

第一个.then里面会全部异步执行完了之后再去执行第二个then里面的

 

const cyList: any = ref([]);
let cyListClone: any = [];
const getUserSecList = async (ownerId: any) => {
    getUserlistInter({
        pageNo: 1,
        pageSize: 20,
        status: 1,
        primaryFlag: 1
    })
        .then((res: any) => {
            if (res.code == 200 || res.code == 0) {
                if (ownerId && ownerId?.length) {
                    ownerId.forEach(async (item: any) => {
                        let ff: any = res.data.userInfoList.find((v: any) => v.id == item.collaborator);
                        cyList.value = [...res.data.userInfoList];
                        if (!ff) {
                            getUserInfoById({ id: item.collaborator }).then((userRes: any) => {
                                if (userRes.code == 0) {
                                    cyList.value.push({
                                        id: userRes.data.id,
                                        nickName: userRes.data.nickName,
                                        userName: userRes.data.userName,
                                        userCode: userRes.data.userCode || ""
                                    });
                                }
                            });
                        }
                    });
                }
            }
        })
        .then(() => {
            postForm.collaboratorList = ownerId?.map((item: any) => item.collaborator);
        })
        .catch((err: any) => {
            console.log("err", err);
        });
};