技术使用: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..
})
答案 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)
就像其他人指出的那样,您可以使+
接受一个回调参数,然后调用它:
secondFunctionAPI
将两个函数都转换为使用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
Promise.all([
firstFunction(), secondFunctionAPI()
]).then(() => {
// ...
});
/ async
await
。async