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

如何等待Promise返回结果后再执行if判断?

Fix: Waiting for a Promise to Resolve Before Executing Your if Logic

No worries about your English at all—let's figure this out together!

The core issue with your code is that when matchPromise exists, you're assigning match to the Promise object itself, not the resolved value of the Promise. By the time your if (match) check runs, the Promise likely hasn't resolved yet, and even after it does, match will never update to the resolved result—it stays a Promise instance. That's why your current logic isn't behaving as you expect.

Here are two simple, reliable solutions:

1. Use async/await (Most Readable Approach)

Wrap your code in an async function, then use await to pause execution until the Promise resolves. This lets you work with the resolved value like a regular variable:

async function processMatch() {
  // Wait for the Promise to resolve if it exists; default to false otherwise
  const match = matchPromise !== undefined ? await matchPromise : false;
  
  if (match) {
    // This code runs ONLY after the Promise resolves (and `match` is truthy)
    console.log("Promise returned a truthy value!");
    // Add your follow-up logic here
  }
}

// Execute the async function
processMatch();

2. Use .then() Chaining (For Non-Async Contexts)

If you can't use async/await (e.g., working in an older JavaScript environment), move your if logic directly inside the .then() callback. This ensures your code runs only after the Promise resolves:

if (matchPromise !== undefined) {
  matchPromise.then(ret_val => {
    if (ret_val) {
      // This runs after the Promise resolves with a truthy value
      console.log("Promise returned a truthy value!");
      // Add your follow-up logic here
    }
  });
} else {
  // Handle the case where `matchPromise` doesn't exist
}

Remember: Promises are asynchronous—you can't access their resolved value synchronously like a standard variable. You need to use either await (in an async function) or .then() to wait for the result before acting on it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:57:15