承诺得到解决,仍然显示待定

时间:2018-05-09 10:12:03

标签: javascript promise

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> }

一旦我解决了这个承诺,它仍然表明它正在等待。第二次,它不打印&#34; goodFun&#34;的内容。 ,有人可以帮助我吗,我错过了什么?

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

1 个答案:

答案 0 :(得分:1)

尊重,这根本不是你如何使用承诺。我建议您完成一些教程,可能是the MDN one

一些问题:

  1. Promise构造函数只接受一个参数。
  2. 该参数必须是promise 执行者函数,它至少接受一个(如果不是两个)参数(您用来解析或拒绝承诺的函数)。
  3. 致电then无法解决承诺。
  4. 在不传递回叫的情况下调用then毫无意义。
  5. 这是你的例子(最好我可以解释它,无论如何)更新为正确使用promises:

    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.