Search code examples
javascriptes6-promise

Why does my 2nd javascript promise call return the same value as the 1st?


Hi I am new to javascript and have recently been learning about promises. I am trying to wait on the result of a network call before moving forward with my logic. To do this I think I need a promise that waits on the network call's result. I have been practicing with promises and noticed some behavior I don't understand.

var mybool = false;

// Promise
var mypromise = new Promise(
    function (resolve, reject) {
        if (mybool) {
            var pvalue = 'PASS';
            resolve(pvalue);
        } else {
            var fvalue = new Error('FAIL');
            reject(fvalue);
        }
    }
);


// call promise
var callpromise = function () {
    mypromise
        .then(function (fulfilled) {
            // yay, you got a new phone
            console.log(fulfilled);
        })
        .catch(function (error) {
            // ops, mom don't buy it
            console.log(error.message);
        });
}

callpromise();
console.log('This will appear first since prev function call is still thinking');
mybool = true;
console.log(mybool);
callpromise();

So as you can see the var mybool determines the output of the promise function. when I run this program this is the output:

"This will appear first since prev function call is still thinking"
true
"FAIL"
"FAIL"

Can someone explain why even after flipping the mybool var the 2ndcallpromise() is still outputting a value I would only expect from mybool = false?


Solution

  • Promises don't get "called", they get created. You create mypromise once, before callpromise gets actually called. By the time, mybool is false. If you want to create a Promise at a specific point in your code, or if you want multiple promises, create the promise inside of a function.