Doing a Timeout Error with Fetch - React Native

前端 未结 6 1364
春和景丽
春和景丽 2021-02-05 15:50

I have a user login function that is working. But, I want to incorporate a time out error for the fetch. Is there a way to set up a timer for 5 seconds or so that would stop try

6条回答
  •  无人及你
    2021-02-05 16:00

    There is no standard way of handling this as a timeout option isn't defined in the official spec yet. There is an abort defined which you can use in conjunction with your own timeout and Promises. For example as seen here and here. I've copied the example code, but haven't tested it myself yet.

    // Rough implementation. Untested.
    function timeout(ms, promise) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(new Error("timeout"))
        }, ms)
        promise.then(resolve, reject)
      })
    }
    
    timeout(1000, fetch('/hello')).then(function(response) {
      // process response
    }).catch(function(error) {
      // might be a timeout error
    })
    

    Another option would be to modify the fetch.js module yourself to add a timeout that calls abort as seen here.

提交回复
热议问题