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

JS中如何获取Promise返回的布尔值,实现直接输出true

解决方案

Promise 是异步操作的封装容器,无法直接在同步上下文中获取内部 resolve 的结果,可通过以下两种方式拿到布尔值 true:

方案1:使用 .then() 回调

这是Promise的标准原生用法,回调函数会在Promise状态变为fulfilled后自动执行,入参就是resolve的结果:

const executorFunction = (resolve, reject) => {
  if (1 === 1) {
   resolve(true);
  } else {
    resolve(false);
  }
}
const myFirstPromise = new Promise(executorFunction);
// 用then回调拿结果
myFirstPromise.then(result => {
  console.log(result) // 输出true
})

方案2:使用 async/await 语法糖

如果偏好更接近同步的写法,可以用await读取Promise结果,注意await只能在async标记的函数中使用,也可在支持顶层await的环境(新版浏览器/Node.js >= 14.8)直接在全局使用:

const executorFunction = (resolve, reject) => {
  if (1 === 1) {
   resolve(true);
  } else {
    resolve(false);
  }
}
const myFirstPromise = new Promise(executorFunction);
// 自执行async函数,兼容不支持顶层await的环境
(async () => {
  const result = await myFirstPromise
  console.log(result) // 输出true
})()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:09:03