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

如何将Twilio获取的短信内容赋值给变量用于后续判断?

解决Twilio短信内容赋值问题

先看你尝试的代码里的两个核心问题:

  • 自定义的resolveAfter2Seconds函数里,Promise没有调用resolve()传递结果,导致await永远拿不到返回值
  • messages.forEach(m => m.body)只是遍历数组,不会返回任何内容;而且你设置了limit:1,直接取数组第一个元素的body更直接

下面是两种修正后的写法,都能把短信内容赋值给变量,方便后续用if做逻辑判断:

写法一:简化版(推荐)

Twilio的client.messages.list()本身就返回Promise,不用额外再包一层Promise,直接用async/await处理更简洁:

async function getLatestMessage() {
  // 调用接口获取指定号码的最新1条短信
  const messages = await client.messages.list({
    from: '123456789',
    limit: 1
  });
  // 取第一条短信的内容(limit=1,数组只有一个元素)
  return messages[0].body;
}

// 主函数:获取结果并执行后续逻辑
async function run() {
  const latestMsg = await getLatestMessage();
  console.log('最新短信内容:', latestMsg);
  
  // 这里写你的if判断逻辑
  if (latestMsg.includes('确认')) {
    console.log('执行确认相关操作');
  } else if (latestMsg.includes('取消')) {
    console.log('执行取消相关操作');
  }
}

run();

写法二:修正你原有的Promise封装

如果想保留自己的Promise结构,记得要调用resolve()把结果传出去:

function getLatestMessage() {
  return new Promise(resolve => {
    client.messages
      .list({
        from: '123456789',
        limit: 1
      })
      .then(messages => {
        // 把短信内容通过resolve传递出去
        resolve(messages[0].body);
      });
  });
}

async function asyncCall() {
  const result = await getLatestMessage();
  console.log(result);
  
  // 示例if逻辑
  if (result === '测试内容') {
    // 执行你需要的操作
    console.log('触发测试操作');
  }
}

asyncCall();

新手必看关键点

  • 所有用await的代码,必须放在async标记的函数里
  • limit:1会返回只有一个元素的数组,所以用messages[0]就能拿到目标短信,再取body就是短信内容
  • Twilio的API方法大多返回Promise,直接用await等待结果就行,不用重复封装Promise

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:20:58