如果网络中断,Promise.race 如何处理?

在使用 Promise.race 时,如果网络中断,通常会导致请求失败,并触发相应的错误处理。这可以通过 Promise.race 中的 Promise 对象来捕获。以下是如何处理网络中断的详细说明。

1. 网络中断的处理

当网络中断时,uni.requestuni.uploadFileuni.downloadFilefail 回调会被触发,你可以在这些回调中拒绝 Promise,并在 Promise.racecatch 方法中处理这个错误。

示例代码

以下是一个包含网络中断处理的 Promise.race 示例,适用于文件上传和下载。

1.1 文件上传示例

javascript 复制代码
function uploadFile(file) {
  const requestTimeout = 5000; // 设置超时时间为 5 秒

  const uploadPromise = new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://example.com/upload',
      filePath: file.path,
      name: 'file',
      formData: {
        otherData: 'value'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(new Error('服务器错误: ' + res.statusCode));
        }
      },
      fail: (error) => {
        reject(new Error('上传失败: ' + error.errMsg)); // 网络中断时会触发这里
      }
    });
  });

  const timeoutPromise = new Promise((_, reject) => {
    setTimeout(() => {
      reject(new Error('上传超时'));
    }, requestTimeout);
  });

  Promise.race([uploadPromise, timeoutPromise])
    .then((data) => {
      console.log('上传成功:', data);
    })
    .catch((error) => {
      if (error.message === '上传超时') {
        console.error('请求超时');
      } else {
        console.error('请求失败或网络中断:', error.message);
      }
    });
}

1.2 文件下载示例

javascript 复制代码
function downloadFile(url) {
  const requestTimeout = 5000; // 设置超时时间为 5 秒

  const downloadPromise = new Promise((resolve, reject) => {
    uni.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath);
        } else {
          reject(new Error('服务器错误: ' + res.statusCode));
        }
      },
      fail: (error) => {
        reject(new Error('下载失败: ' + error.errMsg)); // 网络中断时会触发这里
      }
    });
  });

  const timeoutPromise = new Promise((_, reject) => {
    setTimeout(() => {
      reject(new Error('下载超时'));
    }, requestTimeout);
  });

  Promise.race([downloadPromise, timeoutPromise])
    .then((filePath) => {
      console.log('下载成功:', filePath);
    })
    .catch((error) => {
      if (error.message === '下载超时') {
        console.error('请求超时');
      } else {
        console.error('请求失败或网络中断:', error.message);
      }
    });
}

2. 总结

Promise.race 中,如果发生网络中断,相关的请求 Promise 会被拒绝,并进入到 catch 方法中。

相关推荐
☺����1 分钟前
实现自己的AI视频监控系统-第一章-视频拉流与解码2
开发语言·人工智能·python·音视频
染翰20 分钟前
lua入门以及在Redis中的应用
开发语言·redis·lua
王者鳜錸31 分钟前
PYTHON让繁琐的工作自动化-函数
开发语言·python·自动化
兔老大RabbitMQ1 小时前
git pull origin master失败
java·开发语言·git
tt5555555555551 小时前
C/C++嵌入式笔试核心考点精解
c语言·开发语言·c++
xiao助阵1 小时前
python实现梅尔频率倒谱系数(MFCC) 除了傅里叶变换和离散余弦变换
开发语言·python
朱皮皮呀1 小时前
Spring Cloud——服务注册与服务发现原理与实现
运维·spring cloud·eureka·服务发现·php
吱吱企业安全通讯软件2 小时前
吱吱企业通讯软件保证内部通讯安全,搭建数字安全体系
大数据·网络·人工智能·安全·信息与通信·吱吱办公通讯
科大饭桶2 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
扛麻袋的少年3 小时前
7.Kotlin的日期类
开发语言·微信·kotlin