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

Angular中switchMap订阅未等待setInterval返回undefined问题求助

问题解决:让switchMap等待交易收据状态为true后返回结果

当前你的switchMap返回undefined的核心问题是:

  • async函数内部没有返回一个能传递结果的Promise
  • setInterval里的回调函数无法把rec.result.status传递到外层的switchMap中

下面是修改后的代码,通过Promise封装轮询逻辑,确保直到交易收据状态为true时才返回结果:

switchMap(async (txHash) => {
  console.log("Transaction sent!", txHash);
  return new Promise((resolve, reject) => {
    const interval = setInterval(async () => {
      console.log("Attempting to get transaction receipt...");
      try {
        const rec = await window.web3.eth.getTransactionReceipt(txHash);
        if (rec) {
          clearInterval(interval);
          // 适配web3不同版本的状态值:布尔值或0/1
          const isSuccess = rec.status === true || rec.status === 1;
          if (isSuccess) {
            console.log('success');
            resolve(isSuccess);
          } else {
            reject(new Error("Transaction failed"));
          }
        }
      } catch (err) {
        clearInterval(interval);
        reject(err);
      }
    }, 1000);

    // 可选:添加超时处理,避免无限轮询
    setTimeout(() => {
      clearInterval(interval);
      reject(new Error("Timeout waiting for transaction receipt"));
    }, 60000); // 60秒超时
  });
})

关键说明:

  1. Promise封装:用Promise包裹轮询逻辑,通过resolve传递成功状态,reject处理错误或超时
  2. async/await改造:把getTransactionReceipt的回调形式改为await,代码更简洁易维护
  3. 状态兼容判断:适配web3不同版本中rec.status的类型差异,确保判断准确
  4. 资源清理:无论成功、失败还是超时,都及时清理setInterval,避免内存泄漏
  5. 超时保护:添加超时逻辑,防止程序无限等待

修改后,你的mintNft订阅的next回调就能收到交易成功的状态值,失败或超时会触发error回调:

mintNft(): void {
  this.__mmservice.mintNft().subscribe({
    next: (isSuccess: boolean) => {
      console.log("Transaction succeeded:", isSuccess);
    },
    error: (err: any) => {
      console.log("Transaction failed or timed out:", err);
    },
    complete: () => {
      console.log('123');
    },
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:10:57