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

如何为异步await函数应用RxJS的重试机制?

实现异步函数失败后重试一次的逻辑

我需要让一个返回await异步结果的函数,在首次调用失败时进行一次重试;若第二次调用仍失败,则抛出错误信息。

我的代码如下

async makeCall(inputs: myInputs): Promise<Instance> {

    const emailOptions: CreateOptions = {
      to: inputs.toPhone,
      from: this.config.accountPhoneNumber
    };

    if (inputs.toPhone) {
      emailOptions.sendText = inputs.toPhone;
    }

    return await this.sample.create(emailOptions);
}

我期望实现类似如下逻辑或相关方案(比如RxJS的Retry)

for(var i = 0; i < 2; i++)
{
    var result = await this.sample.create(emailOptions);
    if(result)
    {
        // 跳出循环并返回结果
        return result;
    }
}
// 如果走到这里,说明重试次数已用完
throw Error("调用两次均失败");

方案一:原生异步循环实现重试

无需额外依赖,通过try/catch配合循环实现最多两次调用(首次+1次重试),逻辑直观:

async makeCall(inputs: myInputs): Promise<Instance> {
    const emailOptions: CreateOptions = {
        to: inputs.toPhone,
        from: this.config.accountPhoneNumber
    };

    if (inputs.toPhone) {
        emailOptions.sendText = inputs.toPhone;
    }

    // 最多尝试2次:首次调用 + 1次重试
    for (let attempt = 0; attempt < 2; attempt++) {
        try {
            const result = await this.sample.create(emailOptions);
            // 调用成功则直接返回结果
            return result;
        } catch (error) {
            // 最后一次尝试失败时,抛出包含错误信息的异常
            if (attempt === 1) {
                throw new Error(`调用服务两次均失败: ${(error as Error).message}`);
            }
            // 非最后一次失败,自动进入下一次重试
        }
    }

    // 理论上不会执行到此处,兜底抛出错误
    throw new Error("调用服务失败");
}

方案二:使用RxJS实现重试

如果项目已引入RxJS,可借助其retry操作符简化逻辑:

import { from } from 'rxjs';
import { retry } from 'rxjs/operators';

async makeCall(inputs: myInputs): Promise<Instance> {
    const emailOptions: CreateOptions = {
        to: inputs.toPhone,
        from: this.config.accountPhoneNumber
    };

    if (inputs.toPhone) {
        emailOptions.sendText = inputs.toPhone;
    }

    return from(this.sample.create(emailOptions))
        .pipe(retry(1)) // 指定失败时重试1次
        .toPromise()
        .catch(error => {
            throw new Error(`调用两次均失败: ${(error as Error).message}`);
        });
}

注意事项

  • 确保this.sample.create在调用失败时会抛出错误,否则重试逻辑无法触发
  • 原期望代码中的i < 1循环条件仅会执行一次调用,无法实现重试,需改为i < 2才能覆盖首次+重试的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:13:27