GithubHelp home page GithubHelp logo

Comments (18)

tracker1 avatar tracker1 commented on May 31, 2024 41

Create a timeoutPromise wrapper...

function timeoutPromise(timeout, err, promise) {
  return new Promise(function(resolve,reject) {
    promise.then(resolve,reject);
    setTimeout(reject.bind(null,err), timeout);
  });
}

You can then wrap any promise...

timeoutPromise(100, new Error('Timed Out!'), fetcn(...))
  .then(...)
  .catch(...)

It won't actually cancel an underlying connection, but will allow you to timeout a promise.

from isomorphic-fetch.

jimmywarting avatar jimmywarting commented on May 31, 2024 34

This is how you should be handling abort:

const controller = new AbortController()
const signal = controller.signal

setTimeout(() => { 
  controller.abort()
}, 1000)

fetch(url, { signal })

from isomorphic-fetch.

GabrielDelepine avatar GabrielDelepine commented on May 31, 2024 27

When a client timeout occured, it's very important to cancel the http request.
The fetch api will offer this functionality in a near future with the FetchController.

from isomorphic-fetch.

chrisdevwords avatar chrisdevwords commented on May 31, 2024 23

This isn't handling a timeout for me...

There is an optional "timeout" property you can pass in the options.

fetch(url, {method: 'GET', timeout: 5000})
                .then(response => {
                    if (response.status >= 400) {
                        reject({
                            code: response.status,
                            message: response.statusText
                        });
                    } else {
                        resolve(response.json());
                    }
                })
                .catch(reject);
``

from isomorphic-fetch.

Dindaleon avatar Dindaleon commented on May 31, 2024 22

yes please, add a timeout option

from isomorphic-fetch.

rahulbhanushali avatar rahulbhanushali commented on May 31, 2024 18

+1, please add timeout option

from isomorphic-fetch.

anvk avatar anvk commented on May 31, 2024 17

+1 not sure how to add timeout

from isomorphic-fetch.

raarts avatar raarts commented on May 31, 2024 8

By the way, I solved this neatly in react-native by using redux-saga.

from isomorphic-fetch.

kiorq avatar kiorq commented on May 31, 2024 8

Kinda late here, this is based off of @tyler-canton code he posted up here

function fetch_timeout(url, options = {}) {
    /*
     * fetches a request like the normal fetch function 
     * but with a timeout argument added.
     */
    let timeout = options.timeout || 30000;
    let timeout_err = {
        ok: false,
        status: 408
    };
    return new Promise(function(resolve, reject) {
        fetch(url, options).then(resolve, reject);
        setTimeout(reject.bind(null, timeout_err), timeout);
    });
}

// use
fetch_timeout("http://google.com", {timeout: 500}).then(data => {
    // response here
}).catch(err => {
   // got an error, maybe timeout?
})

This lets you use fetch like how you would normally, but just have an added timeout option. Thanks @tyler-canton!

You might want to change the timeout_err to be an actual error you can check for, for my case this was perfect for what i needed to do.

from isomorphic-fetch.

raarts avatar raarts commented on May 31, 2024 6

Inside a saga, race the fetch call with a timeout like this:

  try {
    const { timeout, response } = yield race({
      timeout: call(delay, 10000),
      response: call(fetch, '<your endpoint>', { parms}),
    });
    if (timeout) {
      console.log('network timeout')
    } else {
      if (response.status === 200) {
        // success
      } else {
        // API error
      }
    }
  }
  catch(error) {
    // Other error by fetch
  }

from isomorphic-fetch.

ianstormtaylor avatar ianstormtaylor commented on May 31, 2024 3

FWIW, I've opened an issue whatwg/fetch#951 with a proposal for a timeout option that solves 90% of use cases, in case anyone's interested. I think it's super important to add to make sure calls to fetch (or res.json()) don't hang indefinitely.

from isomorphic-fetch.

jimmywarting avatar jimmywarting commented on May 31, 2024 3

@ianstormtaylor You really made a number on every single repo that uses the fetch API.
you should only have brought it up with whatwg and then the rest will follow.

from isomorphic-fetch.

JSONRice avatar JSONRice commented on May 31, 2024 2

@kiorq I think you meant to do this:

fetch_timeout("http://google.com", {timeout: 500})

Rather than:

fetch("http://google.com", {timeout: 500})

Also your example doesn't help because all you do is a fetch. Something like the following would be beneficial:

fetchTimeout(copyOfUrl, {timeout: 3}) .then(data => console.log("Data: ", data)) .catch(reason => console.error("Caught error: ", reason.message));

In my case data came back immediately as undefined and I never get the error message after 3 seconds. Tried to fetch this large JSON file:

https://raw.githubusercontent.com/zemirco/sf-city-lots-json/master/citylots.json

from isomorphic-fetch.

dbearscn avatar dbearscn commented on May 31, 2024 1

you can do as fellow:
`fetch("/test", { method: 'POST', body: data })

.then(function(response) {
    if (response.status >= 400) {
        const error = new error("Bad response from server")
        error.response = response
        error.message = "your error message,you can swith the status and set the message"
        throw error
    }
    return response.json();
}).then(function(response) {
    console.log(response)
}).catch(function(e) {
    if (!e.response) {
        e.message = "response time out!"
    }
    return Promise.reject(e);
})`

from isomorphic-fetch.

ducpt2 avatar ducpt2 commented on May 31, 2024

@raarts how redux-saga solve it? Can you post code in here?

from isomorphic-fetch.

JSONRice avatar JSONRice commented on May 31, 2024

For anyone else who gets hung up on Fetch not having timeout you could use the node-fetch rather than native Fetch API. In a lot of cases a timeout isn't necessary but it is necessary if you want to ensure TCP/IP connections close out and don't just have an open socket for some undetermined time. Here's what I ended up doing with node-fetch Works really well:

JakeChampion/fetch#617

from isomorphic-fetch.

sibelius avatar sibelius commented on May 31, 2024

this should be in userLand

from isomorphic-fetch.

ganzf avatar ganzf commented on May 31, 2024

If AbortController is not the solution for you, you can take a peek at this answer on stackoverflow (https://stackoverflow.com/questions/46946380/fetch-api-request-timeout). I found it quite useful !

from isomorphic-fetch.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.