promise与async/await连用全部请求结束时获取请求结果

async/await获取请求结束时机,拿到结果(非promise类型的结果)

  const getModalData = useCallback(async () => {
        const result = await sendRequest(currentCabinet)
        setData(result)
    }, [currentCabinet])

定义promise:因为此处的请求方法结果返回的时promise类型数据(待定状态),故可以直接放入promise.all数组中

  const sendRequest = (data) => {
        const modelId = data.modelId;
        const ciId = data.ciId;
        return new Promise((resolve, reject) => {
            Promise.all([
                getIndexInfo({ modelId, ciId }),
                getConfigInfo({ modelId, ciId }),
                getUpdateInfo({ modelId, ciId }),
                getWarnInfo({ modelId, ciId }),
                getWorkOrderInfo({ modelId, ciId }),
                getInspectionList({ assetsId: ciId }),
                getUbitUsageInfo(ciId),
                getPlanOperationTableData({ assetsId: ciId, field: 'one', order: 'd' }),
                getRelationData({ ciId: ciId })
            ]).then(([indexInfo, configData, updateInfo, warnInfo, workOrderInfo, inspectionList, ubitUsageInfo, planOperationTable, relationData]) => {
                resolve({ indexInfo, configData, updateInfo, warnInfo, workOrderInfo, inspectionList, ubitUsageInfo, planOperationTable, relationData });
            }).catch(error => {
                reject(error);
            });
        });
    };

示例请求方法:

  @action
    getIndexInfo = async (params) => {
        try {
            const res = await fetchIndexInfo(params);
            console.log(res);
            if (res.code === 100000) {
                return res.data
            } else {
                console.error(res.msg);
                return []
            }
        } catch (error) {
            console.error(error);
            return []
        }
    };

 

posted @ 2024-03-18 19:49  SimoonJia  阅读(26)  评论(0编辑  收藏  举报