如何在使用redux的获取承诺中添加setTimeout? [英] How to add a setTimeout to a fetch promise that uses redux?

查看:170
本文介绍了如何在使用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)))
  }
}

这篇关于如何在使用redux的获取承诺中添加setTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆