react hooks中使用promise.all
useEffect(async () => { const getFirstResponse = async () => { try { return await axios.get('http://first-api', { params: { carId: id }, }); } catch (error) { return error; } }; const firstResponse = await getFirstResponse(); const getSecondResponse = async () => { try { return await axios.get('http://second-api', { params: { carName: firstResponse.data?.carName }, }); } catch (error) { return error; } }; const secondResponse = await getSecondResponse(); Promise.all([firstResponse, secondResponse]) .then(function (values) { console.log(`values`, values); }) .catch(function (err) { console.log(err); }); }, []);
const [list, setList] = useState([] as any); const [loading, setLoading] = useState(true); // 页面loading const [imgUrl, setImgUrl] = useState(''); const GetList = async () => { try { const skuList = await request({ api: '接口请求链接' }); setList(skuList?.skuInfoVoList || []); return skuList; } catch (err) { setList([]); return []; } }; const GetBackImg = async () => { const params = { keys: ['onePo', 'ImgUrl'] }; try { const getImgUrl = await request({ api: '接口请求链接', params }); setImgUrl( getImgUrl.oneImgUrl ); return getImgUrl; } catch (err) { console.log(err); return ''; } }; const getAllCont = () => { Promise.all([GetList(), GetBackImg()]) .then(res => { setLoading(false); }) .catch(err => { console.log(err); }); }; useEffect(() => { getAllCont(); }, []);