如何从前端订购一系列 api 调用?

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

我需要从应用程序的 'user profile' 页面进行一系列 API 调用。当我登陆组件时,我需要确定调用的优先级或顺序。

我已经尝试在 componentDidMount 生命周期方法上使用 async-await,但是当第一次调用失败时,其余的不会被调用。

...

async componentDidMount() {

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

}

...

尽管对调用进行了排序,但无论前面的调用是否失败,我都希望它们仍然执行。

这是一个肮脏的解决方案,但你可以这样做:

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

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

如果它们不依赖于先前请求的响应,理想且好的方法是同时异步调用所有它们。

您需要说明被拒绝的承诺。如果您没有发现错误,它将停止执行。只需为每个可能失败的函数添加一个 catch() 块。

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'));
})();

只需在每个 API 调用的末尾添加一个空捕获,如下所示

async componentDidMount() {

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

}

我会 catchnull:

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

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

我还使用了 Promise.all 到 运行 并行调用,因为调用之间似乎没有依赖关系。