【问题标题】:Promise is resolved , still shows pending承诺已解决,仍显示待处理
【发布时间】:2018-05-09 18:25:05
【问题描述】:
function goodFun(){
    console.log('this is good fun');
}
function badFun(){
    console.log('this is bad fun');
}
const promise = new Promise(goodFun , badFun);
console.log(promise); // status , pending 
promise.then(); // resolved 
console.log(promise); // status , still pending !!! how ??? 
promise.then(); // running same promise twice

输出:

this is good fun Promise { <pending> } Promise { <pending> }

一旦我解决了这个承诺,它仍然显示它处于待处理状态。第二次,它没有打印“goodFun”的内容,有人可以帮助我吗,我错过了什么?

更新: 而且, 第一个 console.log(promise) 的输出是在 promise.then() 之后?这也令人困惑?为什么会这样?它应该先打印控制台输出,然后再打印 promise.then()。

【问题讨论】:

  • 谢谢@T.J.Crowder,请阅读更新版本。我不知道为什么 consoleLog 在 promise.then() 之后打印?有什么解释吗?
  • 因为调用 then 并不能解决承诺。同样,我建议您阅读一些教程并研究文档和示例。

标签: javascript promise


【解决方案1】:

恕我直言,这根本不是您使用 Promise 的方式。我建议学习一些教程,也许是the MDN one

一些问题:

  1. Promise 构造函数只接受一个参数。
  2. 该参数必须是一个promise 执行器函数,它至少接受一个(如果不是两个参数)(用于解决或拒绝promise 的函数)。
  3. 调用 then 不会解决承诺。
  4. 不传入回调就调用then 是没有意义的。

这是您的示例(无论如何我都可以解释)更新为正确使用承诺:

const promise = new Promise(function(resolve, reject) {
  // Often a promise is used with asynchronous operations, so let's use
  // setTimeout to emulate one
  setTimeout(function() {
    // Let's give the promise a ~2 in 3 chance of resolving, a ~1 in 3 chance of rejecting
    if (Math.random() >= 1 / 3) {
      console.log("Resolving the promise");
      resolve();
    } else {
      console.log("Rejecting the promise");
      reject();
    }
  }, 100);
});

function goodFun(){
    console.log('this is good fun');
    // Now it's settled (resolved)
    console.log(2, promise);
}
function badFun(){
    console.log('this is bad fun');
    // Now it's settled (rejected)
    console.log(3, promise);
}

promise.then(goodFun, badFun);

// Not settled (resolved or rejected) yet
console.log(1, promise);
You'll have to look in the real console to see the promise internal state, as it's not available to JavaScript code.

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2022-01-20
    • 1970-01-01
    • 2018-04-02
    • 2019-06-16
    • 2023-03-05
    • 2021-03-27
    • 2020-04-21
    • 2017-07-15
    相关资源
    最近更新 更多