MST

星途 面试题库

面试题:Node.js 网络通信超时控制与重试机制的结合实现

假设你在Node.js项目中使用`axios`进行网络请求,在出现超时的情况下,需要实现一个重试机制,最大重试次数为3次,每次重试间隔时间递增1秒(首次重试间隔1秒,第二次2秒,第三次3秒),请给出具体的代码实现思路和关键代码片段。
11.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

代码实现思路

  1. 定义最大重试次数和初始重试间隔时间。
  2. axios请求中设置timeout
  3. 捕获axios请求的超时错误,根据重试次数决定是否进行重试,每次重试增加间隔时间。

关键代码片段

const axios = require('axios');

// 最大重试次数
const maxRetries = 3;
// 初始重试间隔时间(秒)
let retryInterval = 1;

async function makeRequestWithRetry(url, options = {}) {
    let retries = 0;
    while (retries < maxRetries) {
        try {
            // 设置超时时间
            options.timeout = 5000; 
            const response = await axios(url, options);
            return response;
        } catch (error) {
            if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
                retries++;
                if (retries < maxRetries) {
                    console.log(`请求超时,重试第 ${retries} 次,等待 ${retryInterval} 秒...`);
                    await new Promise(resolve => setTimeout(resolve, retryInterval * 1000));
                    retryInterval++;
                } else {
                    console.log('达到最大重试次数,请求失败');
                    throw error;
                }
            } else {
                throw error;
            }
        }
    }
}

// 使用示例
makeRequestWithRetry('https://example.com/api/data')
   .then(response => {
        console.log(response.data);
    })
   .catch(error => {
        console.error('请求最终失败:', error);
    });