返回带有承诺的布尔值

gee*_*972 0 javascript node.js

这是我的代码:

const executorFunction = (解决, 拒绝) => {

<script>
      
if (  1==1){

    resolve(true);
   
}
else{
    resolve(false);
}

    }




const myFirstPromise = new Promise(executorFunction);


console.log(myFirstPromise);


        </script>
Run Code Online (Sandbox Code Playgroud)

这是我的代码的输出:

Promise {<fulfilled>: true}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: true
Run Code Online (Sandbox Code Playgroud)

我想要变量 myFirstPromise 中的布尔值 true

我想要这个输出:

true
Run Code Online (Sandbox Code Playgroud)

请问解决办法是什么?

brk*_*brk 6

你需要使用then. 而且函数script内的标签executorFunction没有任何意义

const executorFunction = (resolve, reject) => {
  if (1 === 1) {
   resolve(true);
  } else {
    resolve(false);
  }

}
const myFirstPromise = new Promise(executorFunction);

myFirstPromise.then(d => console.log(d))
Run Code Online (Sandbox Code Playgroud)

如何从函数中获取变量中的布尔值 true

直接使用 Promise 可能无法实现这一点,您可以使用async function。在内部,这也返回一个 Promise

function executorFunction() {
  return 1 ? true : false;
}

async function getVal() {
  const val = await executorFunction();
  console.log(val)
}

getVal()
Run Code Online (Sandbox Code Playgroud)