请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

如何才能让asyn await 按顺序执行?

hi老师,我有个功能需要,就是需要让request按顺序执行。
比方说,我需要获得用户的request回传之后,再进入下一个request,因为下一个request需要用户的id,然后再接下去的request需要等待上一个request返回,查看返回的code,再接下去,代码如下,请老师帮我看下如何才能实现?谢谢哈!

 const [userToken,setUserToken] = useState('');
  const [loading,setLoading] = useState(true);
   const [data,setData] = useState([]);
 const [me,setMe] = useState({});
  const [likeCount,setLikeCount] = useState(0); 
  const isFocused = useIsFocused();
 let unmounted = false;//组件是否有卸载

  //第一步 : 需要先获取用户的token 
const getMe = async () =>{
   await storage.getToken().then(token=> !unmounted&&setUserToken(token));
}

//第二步,第三步,我使用了promise all ..然后不行..
useEffect(()=>{
getMe();
if(userToken&&!unmounted){
  Promise.all([
    fetch(`${baseUrl}/getMe`,{
     method : "get",
     headers :new Headers({
       'Content-Type':'application/json',
       "Authorization": `Bearer ${userToken}`
      }),
    }).then(res=>res.json()),

    fetch(`${baseUrl}/getAllUsers`,{
     method:'get',
     headers :new Headers({
       'Content-Type':'application/json',
      }),
   }).then(res=>res.json()),
   fetch(`${baseUrl}/getLastLikesCount`,{
    method:'post',
    headers:{
     'Content-Type':'application/json',
     "Authorization": `Bearer ${userToken}`
    },
    body:JSON.stringify({
    _id:me?._id,
    })
  })
  .then(res=>res.json())

  ]).then(([userself,usersinfos,userLikeCounts])=>{
   if(userself&&usersinfos&&userLikeCounts){
     setMe(userself.data);
   }
   if(userself&&usersinfos&&userLikeCounts){
     setData(usersinfos.data)
   }
   if(userself&&usersinfos&&userLikeCounts){
     setLikeCount(userLikeCounts.result);
   }
    setLoading(false);
  }).catch(error=>{
    console.log("获取失败:",error);
    setLoading(true);
  })
}

return ()=>{
  unmounted = true;
}
},[userToken,isFocused,likeCount]);

正在回答

1回答

不要用Promise.all它保障不了顺序的,可以用await 分别执行然后接收结果如:

const r1 = await getr1...
const r2 = await getr2...这里可以使用r1

1 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号