【问题标题】:How to work with a react-geocode promise inside a generator function如何在生成器函数中使用 react-geocode 承诺
【发布时间】:2019-07-23 18:55:01
【问题描述】:

我正在尝试使用 react-geocode 插件,并将它放在 redux saga 的生成器函数中。我对 Promise 和 redux-saga 还是很陌生,所以我不确定这是处理这个插件或一般 Promise 的最佳方式。我正在考虑使用 $scope 在承诺之外调用 lat 和 lng 变量,但我不确定这是否是解决这个问题的最佳方法。最后,lat 和 lng 返回 undefined 但不会捕获错误。

 function* getSearch() {
    const address = yield select(state => state.location.address);
    Geocode.setApiKey("****************");
    console.log(address)
    const a = Geocode.fromAddress(address).then(
        response => {
            const { lat, lng } = response.results[0].geometry.location;
        },
        error => {
            console.error(error);
        }
    )
    try {
        yield put({ type: 'SUCCESS_FETCH_LOCATION', payload: {lat: a.lat, lng: a.lng}})
    } catch (error) {
        console.log(error);
    }
}

【问题讨论】:

    标签: reactjs promise redux-saga google-geocoder


    【解决方案1】:

    如果你产生了一个承诺,redux-saga 将等待该承诺解决,然后在得到结果后恢复你的代码:

    function* getSearch() {
      const address = yield select(state => state.location.address);
      try {
        const response = yield Geocode.fromAddress(address);
        const { lat, lng } = response.results[0].geometry.location;
        yield put({ type: 'SUCCESS_FETCH_LOCATION', payload: { lat, lng }});
      } catch (error) {
        console.log(error);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-10
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2022-07-16
      • 2016-06-22
      • 1970-01-01
      • 2021-10-28
      • 2017-10-20
      相关资源
      最近更新 更多