【问题标题】:Yield in callback generator not activated未激活回调生成器中的收益
【发布时间】:2016-08-10 14:25:39
【问题描述】:

请考虑以下 ES6 函数。我的意图是从谷歌地图获取方向数据。 google map函数以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?

更新: 通常,我在 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')));
  });
});

【问题讨论】:

  • 你是如何调用你的生成器的?能否请您显示您正在使用它的代码?
  • 作为参考,我添加了 UPDATE 部分

标签: ecmascript-6


【解决方案1】:

function* 声明(function 关键字后跟一个星号)定义了一个生成器函数,它返回一个 Generator 对象。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function*

首先你应该实例化生成器函数并从中取回生成器对象。所以我认为回调不会像你期望的那样在这里工作,它会在初始化后停止。

【讨论】:

  • 这是一个好点,在这种情况下,回调生成器不会被实例化。我应该如何控制由生成器的外部库触发的回调?
  • 我可能不得不将回调函数转换为 Promise。正在进行中。
  • 是的,承诺这部分new google.maps.DirectionsService().route({...}) 然后您将能够获得解析值作为生成器并像往常一样使用它。应该在* fetchDirections()之外处理。
猜你喜欢
  • 2013-07-03
  • 2014-06-17
  • 2016-06-24
  • 1970-01-01
  • 2012-08-01
  • 2019-11-28
  • 1970-01-01
  • 2018-08-21
  • 2011-01-22
相关资源
最近更新 更多