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

相关推荐
BingoGo8 小时前
2025 年 PHP 常见面试题整理以及对应答案和代码示例
后端·php
Bruce1231 天前
web专题之php代审(二)
php
白帽黑客沐瑶1 天前
【网络安全就业】信息安全专业的就业前景(非常详细)零基础入门到精通,收藏这篇就够了
网络·安全·web安全·计算机·程序员·编程·网络安全就业
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
BingoGo1 天前
PHP-FPM 深度调优指南 告别 502 错误,让你的 PHP 应用飞起来
后端·php
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
树码小子1 天前
Java网络编程:(socket API编程:TCP协议的 socket API -- 回显程序的服务器端程序的编写)
java·网络·tcp/ip
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题1 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说1 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox