Doing a Timeout Error with Fetch - React Native

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

    I solved this problem by using a race between 2 promises, written as a wrapper around fetch. In my case I expect the request to return json so also added that. Maybe there is a better solution, but this works correctly for me!

    The wrapper returns a promise which will resolve as long as there are no code errors. You can check the result.status for 'success' and read json data from result.data. In case of error you can read the exact error in result.data, and display it or log it somewhere. This way you always know what went wrong!

    var yourFetchWrapperFunction = function (
      method,
      url,
      headers,
      body,
      timeout = 5000,
    ) {
      var timeoutPromise = new Promise(function (resolve, reject) {
        setTimeout(resolve, timeout, {
          status: 'error',
          code: 666,
          data:
            'Verbinding met de cloud kon niet tot stand gebracht worden: Timeout.',
        });
      });
      return Promise.race([
        timeoutPromise,
        fetch(connectionType + '://' + url, {
          method: method,
          headers: headers,
          body: body,
        }),
      ])
        .then(
          (result) => {
            var Status = result.status;
            return result
              .json()
              .then(
                function (data) {
                  if (Status === 200 || Status === 0) {
                    return {status: 'success', code: Status, data: data};
                  } else {
                    return {
                      status: 'error',
                      code: Status,
                      data: 'Error (' + data.status_code + '): ' + data.message,
                    };
                  }
                },
                function (response) {
                  return {
                    status: 'error',
                    code: Status,
                    data: 'json promise failed' + response,
                  };
                },
              )
              .catch((error) => {
                return {status: 'error', code: 666, data: 'no json response'};
              });
          },
          function (error) {
            return {status: 'error', code: 666, data: 'connection timed out'};
          },
        )
        .catch((error) => {
          return {status: 'error', code: 666, data: 'connection timed out'};
        });
    };
    

提交回复
热议问题