当前位置: 首页 > article >正文

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

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

1. 网络中断的处理

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

示例代码

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

1.1 文件上传示例

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 文件下载示例

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 方法中。


http://www.kler.cn/a/547299.html

相关文章:

  • Qwen2-VL 的重大省级,Qwen 发布新旗舰视觉语言模型 Qwen2.5-VL
  • 笔试题笔记#6 模拟三道题和总结知识
  • AI全栈开发_人工智能AI大模型 Prompt提示词工程详解(全方位介绍及运用)
  • 宝塔和docker的区别
  • C++之线程池(Thread Pool)
  • [MySQL]5-MySQL扩展(分片)
  • OpenMetadata MySQL 数据库使用率提取管道实现解析
  • MATLAB中lookBehindBoundary函数用法
  • AcWing——3722. 骑车路线
  • 【C++】基础入门(详解)
  • flutter image_cropper插件安装后 打包apk 报错命名空间问题
  • ShenNiusModularity项目源码学习(8:数据库操作)
  • Python MutableMapping介绍
  • Jetpack Compose系列教程之(10)——State及remeber
  • LabVIEW袜品压力测试系统
  • yolov8断点续练的时候报错如下
  • Linux系统中常见的词GNU是什么意思?
  • 六、面向对象编程(2)
  • STM32之SG90舵机控制
  • 【快速入门】Unity 常用组件(功能块)