简体   繁体   中英

How can I order a series of api calls from the frontend?

I have a series of API calls I need to make from a 'user profile' page on my app. I need to prioritize or order the calls when I land on the component.

I have tried using async-await on the componentDidMount lifecycle method but when the first call fails, the rest do not get called.

...

async componentDidMount() {

  await user.getGameStats();
  await user.getFriendsList();
  await user.getPlayStyle();

}

...

Despite ordering the calls, I would like them to still execute regardless of whether the preceding calls failed.

It's a dirty solution, but you can do something like this:

user.getGameStats().then({res => {
  callGetFriendsList();
}).catch({err => 
  callGetFriendsList();
});

function callGetFriendsList() {
  user.getFriendsList().then(res => {
    user.getPlayStyle();
  }).catch(err => {
    user.getPlayStyle();
  });
}

The ideal and good way would be to call all of them at the same time asynchronously if they are not dependent on the response of the previous request.

You need to account for rejected promises. If you don't catch the error it will stop execution. Just add a catch() block to each function that may fail.

 function a(){ return new Promise((r,f)=>{ console.log('a'); r(); }); } function b(){ return new Promise((r,f)=>{ console.log('b'); f(); // rejecting this promise }); } function c(){ return new Promise((r,f)=>{ console.log('c'); r(); }); } async function d(){ throw new Error('Something broke'); } (async ()=>{ await a().catch(()=>console.log('caught a')); await b().catch(()=>console.log('caught b')); await c().catch(()=>console.log('caught c')); await d().catch(()=>console.log('caught d')); })(); 

Just add an empty catch at the end of each API call as following

async componentDidMount() {

  await user.getGameStats().catch(err=>{});
  await user.getFriendsList().catch(err=>{});
  await user.getPlayStyle().catch(err=>{});

}

I'd catch to null :

  const nullOnErr = promise => promise.catch(() => null);

 async componentDidMount() {
   const [gameStats, friendsList, playStyle] = await Promise.all([
     nullOnErr(user.getGameStats()),
     nullOnErr(user.getFriendsList()),
     nullOnErr(user.getPlayStyle())
    ]);
    //...
 }

I also used Promise.all to run the calls in parallel as there seems to be no dependency between the calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM