Doing a Timeout Error with Fetch - React Native

前端 未结 6 1386
春和景丽
春和景丽 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:20

    I may be late but i made a code which is 100% working to timeout an API request using fetch.

    fetch_timeout(url, options) {
      let timeout = 1000;
      let timeout_err = {
        ok: false,
        status: 408,
      };
      return new Promise(function (resolve, reject) {
        fetch(url, options)
          .then(resolve, reject)
          .catch(() => {
            alert('timeout.');
          });
        setTimeout(reject.bind(null, timeout_err), timeout);
      });
    }
    

    You just need to pass the api-endpoint to the url and body to the options parameter.

提交回复
热议问题