使用提取执行超时错误-React Native [英] Doing a Timeout Error with Fetch - React Native

查看:86
本文介绍了使用提取执行超时错误-React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在运行的用户登录功能.但是,我想为获取合并一个超时错误.有没有一种方法可以将计时器设置为5秒钟左右,以便在这样的时间后停止尝试获取?否则,过一会儿说网络错误,我只会出现红屏.

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 trying to fetch after such a time? Otherwise, I just get a red screen after a while saying network error.

_userLogin() {
  var value = this.refs.form.getValue();
  if (value) {
    // if validation fails, value will be null
    if (!this.validateEmail(value.email)) {
      // eslint-disable-next-line no-undef
      Alert.alert('Enter a valid email');
    } else {
      fetch('http://51.64.34.134:5000/api/login', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        timeout: 5000,
        body: JSON.stringify({
          username: value.email,
          password: value.password,
        }),
      })
        .then((response) => response.json())
        .then((responseData) => {
          if (responseData.status == 'success') {
            this._onValueChange(STORAGE_KEY, responseData.data.token);
            Alert.alert('Login Success!');
            this.props.navigator.push({name: 'StartScreen'});
          } else if (responseData.status == 'error') {
            Alert.alert('Login Error', responseData.message);
          }
        })
        .done();
    }
  }
}

推荐答案

我制作了一个ES6函数,该函数将ES提取包装为一个承诺,这里是:

I have made a ES6 function that wraps ES fetch into a promise, here it is:

export async function fetchWithTimeout(url, options, timeout = 5000) {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
    ]);
}

这里是使用方法:

const requestInfo = {
    method,
    headers,
    body,
};
const url = 'http://yoururl.edu.br'
let data = await fetchWithTimeout(url, requestInfo, 3000);

这篇关于使用提取执行超时错误-React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆