如果网络中断,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 方法中。

相关推荐
CHENKONG_CK9 分钟前
破解制鞋打磨痛点:RFID赋能去毛刺工序自动化升级
网络·单片机·嵌入式硬件·网络协议·tcp/ip
伞伞悦读28 分钟前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
chshang199234 分钟前
工业路由器是什么?浅谈5G工业网络中的IR602
网络·物联网·5g·智能路由器
CCCCCCCCharlie36 分钟前
Linux进程控制四大核心操作
linux·开发语言
萧瑟余晖1 小时前
Netty 核心组件与 Reactor 模型详解
网络·架构
Brilliantwxx1 小时前
【STM32】 SPI Flash 驱动开发实战:阻塞模式驱动 W25Q64(含工程代码)
开发语言·stm32·单片机·嵌入式硬件
ITxiaobing20231 小时前
IP 定位服务选型指南:从准确率到工程落地的技术考察
linux·服务器·网络
wuyk5551 小时前
【Socket 进阶之路】第 9 章 Linux 网络服务量产稳定性优化|心跳保活、TIME_WAIT、SO_LINGER、内存池、断线重连、完整异常防护框架
linux·服务器·开发语言·网络·物联网
邪修king1 小时前
Re:Linux 系统篇(三十四):进程间通信开篇Chapter1 —— 匿名管道 pipe 深度拆解与代码实战
android·linux·运维·开发语言