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

使用JS Promise实现中断遇问题:为何修改条件后Promise仍处于pending状态?

问题原因分析

你的代码里Promise一直处于pending状态的核心原因是:Promise的executor回调函数是在创建Promise的瞬间同步执行的。

当你执行new Promise(...)时,里面的代码立刻就运行了——这时候count的值是1,count == 2的条件不成立,所以resolve("hello")根本没被调用。之后你把count改成2,executor函数不会再重新执行,Promise自然一直卡在pending状态。

实现需求的几种方案

既然你不想用轮询,要的是“条件满足时主动触发”的效果,以下几种方案更贴合你的需求:

方案1:自定义事件触发(通用环境)

通过EventTarget创建事件触发器,当count满足条件时主动触发事件,监听事件的地方执行逻辑:

class CountWatcher extends EventTarget {}
const watcher = new CountWatcher();

// 监听条件满足的事件
watcher.addEventListener('count-ready', () => {
  console.log("hello");
});

let count = 1;
console.log("1 now");
count = 2;

// 条件达成时触发事件
if (count === 2) {
  watcher.dispatchEvent(new Event('count-ready'));
}

方案2:用Proxy监听变量变化

通过Proxy拦截count的赋值操作,当值变为2时直接执行回调:

let count = 1;
const handler = {
  set(target, prop, value) {
    target[prop] = value;
    // 检查条件
    if (value === 2) {
      console.log("hello");
    }
    return true;
  }
};
const proxyCount = new Proxy({ count }, handler);

console.log("1 now");
// 修改代理变量触发拦截逻辑
proxyCount.count = 2;

方案3:Promise封装+手动触发(适配Promise链式场景)

如果你的逻辑必须基于Promise,可以把resolve函数暴露出来,在条件满足时手动调用:

let resolvePromise;
const p = new Promise((resolve) => {
  resolvePromise = resolve; // 保存resolve引用
});

p.then((msg) => {
  console.log(msg);
});

let count = 1;
console.log("1 now");
count = 2;

// 条件满足时手动触发resolve
if (count === 2) {
  resolvePromise("hello");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:48:15