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

相关推荐
脏脏a10 分钟前
C 语言分支与循环:构建程序逻辑的基石
c语言·开发语言
gma99918 分钟前
【RTSP】客户端(一):RTSP协议实现
网络
结衣结衣.34 分钟前
【Qt】带参数的信号和槽函数
开发语言·qt·c++11
冷琴199636 分钟前
基于Python+Vue开发的电影订票管理系统源码+运行步骤
开发语言·vue.js·python
L Jiawen37 分钟前
【Python 2D绘图】Matplotlib绘图(统计图表)
开发语言·python·matplotlib
Run_Teenage1 小时前
C语言每日一练——day_4
c语言·开发语言
SongYuLong的博客1 小时前
C# WPF 串口通信
开发语言·c#·wpf
熊峰峰1 小时前
数据结构第六节:二叉搜索树(BST)的基本操作与实现
开发语言·数据结构·c++·算法
追寻向上1 小时前
《JMeter自动化测试实战指南:从环境搭建到Python集成》
开发语言·python·jmeter