fetch设置网络超时时间

本文介绍了如何利用Promise.race方法为fetch请求设置网络超时时间,当fetch请求超过预设时间未完成时,会自动终止请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 let promise = new Promise((resolve, reject) => {
            this.timer = setTimeout(() => {
                reject(new Error('超时了'));
            }, 20000);
        }).then((data) => {

        }).catch((e) => {
        });

        let httpPromise=new Promise((resolve, reject) => {
            fetch('https://xxxxxxxx/Login?name=18521596304&pwd=123456')
                .then((res) => {
                    //如果登录接口返回成功,那么把返回的json返回回去
                    return res.json();
                }).then((json) => {
                resolve(json);


            }).catch((e) => {
                //如果失败,把错误返回回去。
                reject(e);

            })
        });

        Promise.race([promise,httpPromise ])
            .then((json) => {
                this.LoadingDialog.close();
                if (json.Statu == 1) {
                    this.props.login_in(json.Data);
                } else {
                    this.props.loginFail();
                }
                new Promise((resolve, reject) => {
                    this.timer = setTimeout(() => {
                        resolve();
                    }, 500)
                }).then(() => {
                    Alert.alert('提示', json.Msg, [{
                        text: '确定', onPress: () => {
                        }
                    }], {cancelable: false});
                }).catch((e) => {
                    console.log("出现异常" + e.toString());
                });
            }).catch((e) => {
            this.LoadingDialog.close();
            new Promise((resolve, reject) => {
                this.timer = setTimeout(() => {
                    resolve();
                }, 500)
            }).then(() => {
                Alert.alert('提示', e.toString(), [{
                    text: '确定', onPress: () => {

                    }
                }], {cancelable: false});
            });
        })
        ;

关键方法 promise.race([]);当里面的某一个方法触发了resolve或者reject之后,其他的promise的resolve和reject将不会再触发。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值