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

Bun运行环境下ElysiaJS中Twilio客户端Promise无法解决求助

问题分析与解决方案

你的代码在Bun+ElysiaJS环境下调用Twilio Verification API时,Promise无法resolve、代码卡在await处,但Twilio后台显示请求成功,核心原因是Twilio官方Node.js SDK与Bun运行时存在兼容性差异——Bun的网络IO实现和Node.js不完全一致,依赖Node.js特定API的SDK可能出现异步阻塞问题。

以下是几种可行的解决方案,按优先级排序:

1. 改用原生HTTP请求绕开SDK

直接用Bun内置的fetch调用Twilio的Verification Check API,完全不依赖官方SDK,从根源上避免兼容性问题:

async verifyWithOTP(phone: string, otp: string) {
  console.log({ phone, otp });
  try {
    console.log("awaiting verification");
    // 替换为你的Twilio账号信息
    const accountSid = "你的Twilio Account SID";
    const authToken = "你的Twilio Auth Token";
    const serviceSid = "VA32f14036285fccdcc0a7ac76ac424515";
    
    const response = await fetch(
      `https://verify.twilio.com/v2/Services/${serviceSid}/VerificationCheck`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          // 生成Twilio基础认证头
          Authorization: `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString("base64")}`
        },
        body: new URLSearchParams({
          to: phone,
          code: otp
        })
      }
    );

    if (!response.ok) {
      const errorData = await response.json();
      console.log("failed to verify:", errorData);
      return false;
    }

    const verification = await response.json();
    console.log(verification.status);
    console.log("verification successful");
    return true;
  } catch (error) {
    console.log("failed to verify:", error);
    return false;
  }
}

2. 给SDK调用添加超时机制

如果不想放弃SDK,可以给await操作设置超时,防止代码无限阻塞:

async verifyWithOTP(phone: string, otp: string) {
  console.log({ phone, otp });
  try {
    console.log("awaiting verification");
    
    const verificationPromise = client.verify.v2
      .services("VA32f14036285fccdcc0a7ac76ac424515")
      .verificationChecks.create({
        to: phone,
        code: otp,
      });

    // 设置5秒超时,可根据需求调整
    const verification = await Promise.race([
      verificationPromise,
      new Promise((_, reject) => setTimeout(() => reject(new Error("Verification timed out")), 5000))
    ]);

    console.log(verification.status);
    console.log("verification successful");
    return true;
  } catch (error) {
    console.log("failed to verify:", error);
    return false;
  }
}

注意:这只是临时 workaround,无法解决SDK本身的兼容性问题,后续可能仍会出现异常。

3. 切换到Node.js运行环境

如果上述方案都无法解决问题,再考虑切换到Node.js(搭配Express、NestJS等框架),Twilio官方SDK在Node.js环境下完全兼容,能保证稳定运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:33:37