使用 Async 并等待 Fetch(在 Redux 的 Actions 中)ReactJS

Using Async and await with Fetch (in Actions of Redux) ReactJS

我试图通过单击按钮一个接一个地调用多个 API。像这样的东西。然后路由到不同的路径。

 onRowClick = (id) => {
  this.props.selectQuestionnaire(id)
  this.props.getSpecificQuestionnaireAQ(id)
  this.props.getAQoptions(id)
  this.props.getAQResultarray(id)
  history.push('/answerques')
};

所有这些都被指定为 redux 层中的动作,我正在使用 fetch 库来进行这些 API 调用一个这样的动作的例子是:

export function getAQResultarray(aqid){
  return function(dispatch){
    console.log("fetching specific AQ")
    var myHeaders = new Headers();
    myHeaders.append('Accept' ,  'application/json');
    myHeaders.append('Content-Type' ,  'application/json');
    myHeaders.append('x-Auth-Token' ,  localStorage.getItem('authtoken'));

    const myInit = {
      headers: myHeaders,
      credentials : 'same-origin'
    };

    var url="http://10.00.000.00:000/abc/api/v1/"+aqid
    console.log(url);
    var myRequest = new Request(url)
    fetch(myRequest, myInit)
      .then((response) => {
        console.log("Response for aq responses  notfications : ",response)
        return response.json();
      })
      .then((tokenData) => {
        console.log("posting aq responses specific  : ",tokenData);
        dispatch({
        type : AQ_RESPONSEARRAY,
        payload : tokenData
      })})
      .catch((error) => {
        console.log(error);
      });
  }
};

如何使此代码的行为使 API 调用以同步方式发生?我的意思是,每个动作只有在前一个动作完成后才会被调用。

我听说过promise,还有async/await。哪个更容易实施?

如果我正确理解你的问题,你只想链接最后一段代码,即重定向。虽然这些操作完全可以并行 运行。为实现这一目标,您的动作创作者应该return承诺不破坏承诺链。

onRowClick = (id) => {
  // run all actions in parallel
  Promise.all([this.props.selectQuestionnaire(id)
    this.props.getSpecificQuestionnaireAQ(id)
    this.props.getAQoptions(id)
    this.props.getAQResultarray(id)])
  .then(() =>  history.push('/answerques'))
};

将动作创建者修复为 return 来自 thunk 的承诺。

export function getAQResultarray(aqid){
  return function(dispatch){
    console.log("fetching specific AQ")
    var myHeaders = new Headers();
    myHeaders.append('Accept' ,  'application/json');
    myHeaders.append('Content-Type' ,  'application/json');
    myHeaders.append('x-Auth-Token' ,  localStorage.getItem('authtoken'));

    const myInit = {
      headers: myHeaders,
      credentials : 'same-origin'
    };

    var url="http://10.00.000.00:000/abc/api/v1/"+aqid
    console.log(url);
    var myRequest = new Request(url)

    // NB! return statement
    return fetch(myRequest, myInit)
      .then((response) => {
        console.log("Response for aq responses  notfications : ",response)
        return response.json();
      })
      .then((tokenData) => {
        console.log("posting aq responses specific  : ",tokenData);
        dispatch({
        type : AQ_RESPONSEARRAY,
        payload : tokenData
      })})
      .catch((error) => {
        console.log(error);
      });
  }
};

如果你真的想要一个接一个地 运行 动作(但我怀疑你真的需要它)你最好至少在处理程序中坚持使用 async/await 语法。但无论如何,你的动作创作者的 thunks 最终应该 return 一个承诺。

onRowClick = async (id) => {    
  await this.props.selectQuestionnaire(id)
  await this.props.getSpecificQuestionnaireAQ(id)
  await this.props.getAQoptions(id)
  await this.props.getAQResultarray(id)
  history.push('/answerques')
};