它告诉我“承诺不是一种功能”。我的问题是,使用同构提取,你必须放两次才能得到你的解析结果。如何使用redux-saga生成器正确管理?
import { put, call, takeEvery, takeLatest } from 'redux-saga/effects'
import fetch from 'isomorphic-fetch'
import errorMessages from './../conf/errorMessages'
function *fetchBalances(address) {
try {
var request = fetch('/api/getBalances/rJnZ4YHCUsHvQu7R6mZohevKJDHFzVD6Zr').then(function(response) {
return response.json();
}). then(function(result) {
// finally my parsed result !
return result;
});
const balances = yield call(request)
yield put({ type: 'GET_BALANCES_SUCCEED', balances: balances})
}
catch(error) {
yield put({ type: 'GET_BALANCES_ERROR', error: error })
}
}
export function* watchGetBalances() {
yield takeEvery('GET_BALANCES', fetchBalances);
}
我可以把它放在封闭中,但这是最好的主意吗? = /
var request = function() {
return fetch('/api/getBalances/rJnZ4YHCUsHvQu7R6mZohevKJDHFzVD6Zr').then(function(response) {
return response.json();
}). then(function(result) {
return result;
});
}
答案 0 :(得分:0)
这里的混淆来自于您传递给request
效果的call
变量持有Promise
这一事实。你想要的是为你执行Promise的call
效果。
换句话说,您已经手动调用fetch
函数,而不是传递call
将调用并返回它的函数。
所以,是的,将你的提取调用包装在例如。 callRequest
函数可能很有用但是如果你这样做,你必须小心写const response = yield call(callRequest)
,而不是const response = yield call(callRequest())
,这等同于你所写的内容。
一些精确性,如果有帮助的话。从文档中,call
收到第一个参数:
生成器函数或正常函数,它返回Promise作为结果或任何其他值。
让我们看看它是如何运作的。
首先是生成器功能。
const response = yield call(myFunction);
function* myFunction() {
yield delay(1000);
return true;
}
// response === true
然后一个函数返回一些值(不是最有用的,但是......)
const response = yield call(myFunction);
function myFunction() {
return true;
}
// response === true;
最后一个函数返回一个Promise
const response = yield call(callRequest);
function callRequest() {
return fetch(…).then( r => r.json() )
}
// response holds your data
// if the Promise were to be rejected, you could catch
// the error in a try-catch block