You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过While循环Promise/链式Promise实现3次服务器连接失败后跳转页面

实现3次服务器连接重试+失败跳转逻辑的解决方案

嘿,我来帮你搞定这个3次重试的逻辑!结合你现有的代码,我会给出两种易读的实现方式,你可以按需选择。

首先明确核心需求:最多尝试3次连接服务器,全部失败就跳转到"No Connection"页面。现在基于你的现有代码修改:

完整修改后的代码(推荐async/await写法,可读性更高)

const fetchModule = require('fetch');
const frameModule = require('ui/frame');

let timeTrig;
const waitPeriod = 7000;
const MAX_RETRIES = 3; // 定义最大重试次数

// 封装带重试逻辑的连接函数
async function attemptServerConnection(retriesLeft = MAX_RETRIES) {
  try {
    // 替换成你实际的服务器请求地址
    const response = await fetchModule.fetch('https://your-server-api.com/status');
    
    // 检查服务器响应是否正常
    if (!response.ok) {
      throw new Error(`服务器返回错误状态: ${response.status}`);
    }
    
    // 连接成功,处理响应(这里根据你的需求调整,比如返回JSON)
    const serverData = await response.json();
    console.log('服务器连接成功:', serverData);
    return serverData;
  } catch (error) {
    console.error(`连接失败,剩余重试次数: ${retriesLeft - 1}`, error);
    
    if (retriesLeft > 1) {
      // 重试前等待7秒(可根据需求调整或移除)
      await new Promise(resolve => setTimeout(resolve, waitPeriod));
      // 递归调用,减少重试次数
      return attemptServerConnection(retriesLeft - 1);
    } else {
      // 所有重试都失败,跳转至无连接页面
      frameModule.topmost().navigate('views/no-connection/no-connection');
      throw new Error('全部3次连接尝试均失败');
    }
  }
}

// 修改原有的检查函数,调用重试逻辑
function checkServerStatus() {
  if (timeTrig) {
    clearTimeout(timeTrig);
  }
  
  attemptServerConnection()
    .then(() => {
      // 如果需要定期检查服务器状态,连接成功后重新设置定时器
      timeTrig = setTimeout(checkServerStatus, waitPeriod);
    })
    .catch(finalError => {
      // 所有重试失败的情况已经处理了跳转,这里可以做额外的错误日志
      console.error('最终连接失败:', finalError);
    });
}

// 启动检查(比如在页面加载时调用)
checkServerStatus();

另一种纯Promise链式写法(不用async/await)

如果你更习惯传统的Promise链式调用,也可以用这个版本:

const fetchModule = require('fetch');
const frameModule = require('ui/frame');

let timeTrig;
const waitPeriod = 7000;
const MAX_RETRIES = 3;

function attemptServerConnection(retriesLeft = MAX_RETRIES) {
  return fetchModule.fetch('https://your-server-api.com/status')
    .then(response => {
      if (!response.ok) {
        throw new Error(`服务器返回错误状态: ${response.status}`);
      }
      return response.json();
    })
    .catch(error => {
      console.error(`连接失败,剩余重试次数: ${retriesLeft - 1}`, error);
      
      if (retriesLeft > 1) {
        // 等待后重试
        return new Promise(resolve => setTimeout(resolve, waitPeriod))
          .then(() => attemptServerConnection(retriesLeft - 1));
      } else {
        frameModule.topmost().navigate('views/no-connection/no-connection');
        throw new Error('全部3次连接尝试均失败');
      }
    });
}

function checkServerStatus() {
  if (timeTrig) {
    clearTimeout(timeTrig);
  }
  
  attemptServerConnection()
    .then(() => {
      timeTrig = setTimeout(checkServerStatus, waitPeriod);
    })
    .catch(finalError => {
      console.error('最终连接失败:', finalError);
    });
}

checkServerStatus();

关键细节说明

  • 重试逻辑:通过递归调用attemptServerConnection函数,每次失败后减少重试次数,直到次数耗尽。
  • 失败跳转:当最后一次重试失败时,调用frameModule.topmost().navigate()跳转到你的"No Connection"页面,记得替换成你项目中实际的页面路径。
  • 定时器保留:保留了你原有代码中的定时逻辑,连接成功后会每隔7秒再次检查服务器状态,如果不需要这个功能,可以移除timeTrig = setTimeout(checkServerStatus, waitPeriod);这一行。
  • 响应处理:根据你的实际需求调整服务器响应的处理逻辑,比如如果不需要JSON数据,可以直接返回response或者做其他操作。

内容的提问来源于stack exchange,提问作者Loki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:33:12