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

Output :

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

Once I have resolved the promise, still it shows that it's pending. and second time, it doesn't print the content of "goodFun" , can someone help me, what am I missing ?

UPDATE : Moreover, output of the first console.log(promise) is AFTER the promise.then() ? that's also confusing ? why does it happen ? It should print console output first and then promise.then() second.

Neer Patel
  • 399
  • 3
  • 11
  • thank you @T.J.Crowder ,please read the updated version. I don't know why consoleLog is printed after promise.then() ? any explanation ? – Neer Patel May 09 '18 at 10:17
  • Because calling `then` doesn't resolve a promise. Again, I do suggest working through some tutorials and studying documentation and examples. – T.J. Crowder May 09 '18 at 10:17

1 Answers1

1

With respect, that's not at all how you use promises. I suggest working through some tutorials, perhaps the MDN one.

Some issues:

  1. The Promise constructor accepts only one parameter.
  2. That parameter must be a promise executor function which accepts at least one if not two parameters (the functions you'd use to resolve or reject the promise).
  3. Calling then does not resolve a promise.
  4. Calling then without passing in a callback is pointless.

Here's your example (as best I can interpret it, anyway) updated to use promises correctly:

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.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875