如何在使用redux的获取承诺中添加setTimeout?

如何在使用redux的获取承诺中添加setTimeout?

问题描述:

经过一定的秒数后,如果尚未解决获取承诺,我想向用户显示超时错误.

After a certain amount of seconds if a fetch promise has not been resolved I want to show a timeout error to the user.

我已经看到了一些添加setTimeout以便在此处获取的好例子: https://github.com/github/fetch/issues/175

I've seen some good examples of adding a setTimeout to fetch here: https://github.com/github/fetch/issues/175

但是我该如何处理也使用redux的获取承诺超时呢?例如

But how can I handle timing out a fetch promise that also uses redux? E.g.

export function getData() {
  return (dispatch, getState) => {
    fetch('blah.com/data')
    .then(response => response.json())
    .then(json => dispatch(getDataSuccess(json)))
    .catch(
      error => {
        console.log(error)
      }
    )
      dispatch({
        type: DATA_FETCH_REQUEST
      })
  }
}

感谢阅读!

我一直渴望使用Promise.race的原因,它非常适合该用例. Promise.race等待第一个解决或第一个拒绝.因此,如果拒绝首先触发,那么它将永远不会触发Promise.race上的then.此处更多 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/race .抱歉,我没有机会测试代码.

I've been dying to have a reason use Promise.race, it works perfectly for this use case. Promise.race waits for the first resolve or first reject. So if reject fires first then it will never fire the then on Promise.race. More here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race. Sorry, I didn't get a chance to test the code.

export function getData() {
  return (dispatch, getState) => {
    let timeout = new Promise((resolve, reject) => {
      setTimeout(reject, 300, 'request timed out');
    })
    let fetch = new Promise((resolve, reject) => {
      fetch('blah.com/data')
        .then(response => response.json())
        .then(json => resolve(json))
        .catch(reject)
    })
    return Promise
      .race([timeout, fetch])
      .then(json => dispatch(getDataSuccess(json)))
      .catch(err => dispatch(getDataTimeoutOrError(err)))
  }
}