使用react / redux saga异步api调用后如何访问数据?以下更多信息

时间:2020-05-12 23:46:41

标签: reactjs api redux redux-saga saga

技术使用:React,Redux,Saga 从第二个函数调用后如何访问数据? firstFunction继续执行其余代码。我尝试了async / await,但无法正常工作。

   firstFunction (()=>{
  secondFunctionAPI() //using Redux and Saga
   // Here I want to use the data from the response of secondFunction().
more code...
more code..
})

3 个答案:

答案 0 :(得分:0)

您可以将要执行的代码作为回调传递给secondFunctionAPI

firstFunction(() => {
  secondFunctionAPI((data) => {
    // Code using data object
  })
})

secondFunctionAPI看起来像这样:

secondFunctionAPI = (callback) => {
  API.fetchSomething().then(response => {
    // Call back with data object
    callback(response.data);
  }) 
}

答案 1 :(得分:0)

您可以通过在api调用后调度一个动作来调用第二个函数,如下所示:

const response = yield call(firstFunction);
yield put({ type: 'SOME_ACTION', payload: response.data });

然后定义了一个观察者传奇,将等待类型为'SOME_ACTION'的动作,并在分派此动作后调用处理程序。

yield takeLatest('SOME_ACTION', second function)

然后为“ SOME_ACTION”定义处理程序,如:

function* secondFunction(action) {
  // here action is the object which was sent as param in put() method earlier
  const { type, payload } = action;
  // your logic here
}

答案 2 :(得分:0)

方法1:回调

就像其他人指出的那样,您可以使+接受一个回调参数,然后调用它:

secondFunctionAPI

方法2:承诺

将两个函数都转换为使用Promise,例如:

firstFunction (() => {
  secondFunctionAPI(() => {
    // More code here...
  });
});

然后,像这样调用您的函数:

function secondFunctionAPI(){
  return new Promise((resolve, reject) => {
    // do stuff, then:
    resolve();
  });
}

firstFunction().then(() => { secondFunctionAPI().then(() => { // More code here... }); });

如果您可以同时调用两个函数(secondFunctionAPI不需要运行firstFunction的结果),则可以使用它来提高效率:

Promise.all

方法3:Promise.all([ firstFunction(), secondFunctionAPI() ]).then(() => { // ... }); / async

  1. 使函数像上面那样返回promise。
  2. 制作包装器await
async