请考虑以下ES6功能。我的目的是从谷歌地图中获取方向数据。谷歌地图功能将origin,destination,travelMode和callback作为参数。
// Get direction data from Google API. Individual exports for testing
export function* fetchDirections() {
const mapApiGoogle = yield select(selectMapApiGoogle());
const google = mapApiGoogle.library;
const origin = yield select(selectOrigin());
const destination = yield select(selectDestination());
new google.maps.DirectionsService().route({
origin: new google.maps.LatLng(origin.lat, origin.lng),
destination: new google.maps.LatLng(destination.lat, destination.lng),
travelMode: google.maps.TravelMode.DRIVING,
}, function* (result, status) {
if (status === google.maps.DirectionsStatus.OK) {
yield put(MapDirectionsRequestedGoogleSuccess(result));
} else {
yield put(MapDirectionsRequestedGoogleError(result));
}
}
);
}
问题是,当执行DirectionService()。route()函数并调用带有结果的回调时,我的fetchDirections()生成器无法识别回调中的yield。我应该如何修改上面的代码才能在回调函数中利用yield?
UPDATE:通常情况下,我在redux-saga中使用生成器。出于测试目的,我调用如下的生成器。我刚刚意识到,回调生成器没有实例化,因此永远不会达到内部产量。你知道如何从fetchDirections()控制内部回调生成器或如何测试结果?
describe('fetchDirections', () => {
let fetchSaga = false;
const googleStub = {
maps: {
LatLng: function (lat, lng) {
return { lat, lng }
},
TravelMode: {
DRIVING: 'DRIVING'
},
DirectionsStatus: {
OK: 'OK'
}
}
};
beforeEach(() => {
fetchSaga = fetchDirections();
const selectDescriptor = fetchSaga.next().value;
expect(selectDescriptor).toEqual(select(selectMapApiGoogle()));
});
it('should invoke directions api', () => {
googleStub.maps.DirectionsService = () => {
return {
route: function(origin, destination, travelMode, callback) {
callback('directions','OK');
}
}
};
const putDescriptor = fetchSaga.next({ library: googleStub }).value;
expect(putDescriptor).toEqual(put(MapDirectionsRequestedGoogleSuccess('directions')));
});
});
答案 0 :(得分:1)
函数*声明(函数关键字后跟星号)定义了一个生成器函数,它返回一个Generator对象。
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function *
首先,您应该实例化Generator函数并从中获取生成器对象。所以我认为回调不会像你期望的那样在这里工作,它会在初始化后停止。