Doing a Timeout Error with Fetch - React Native

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

    This is what I did to go around it: (This is the "generic" function I use to make all calls on my app)

    I created a timeout function, that will be triggered unless it is cleared before, then I clear this timeout on server response

    const doFetch = (url, callback, data) => {
      //... creating config obj here (not relevant for this answer)
      var wasServerTimeout = false;
      var timeout = setTimeout(() => {
        wasServerTimeout = true;
        alert('Time Out');
      }, 3000);
      fetch(HOST + url, config)
        .then((response) => {
          timeout && clearTimeout(timeout); //If everything is ok, clear the timeout
          if (!wasServerTimeout) {
            return response.json();
          }
        })
        .then((response) => {
          callback && callback(response.data || response);
        })
        .catch((err) => {
          //If something goes wrong, clear the timeout
          timeout && clearTimeout(timeout);
          if (!wasServerTimeout) {
            //Error logic here
          }
        });
    };
    

提交回复
热议问题