Search code examples
javascriptecmascript-6javascript-objectses6-promise

Are resolve and reject in Javascript promises methods or just some variables?


take the below example code

var promise = new Promise(function(resolve, reject) { 
const x = "geeksforgeeks"; 
const y = "geeksforgeeks"
if(x === y) { 
    resolve(); 
} else { 
    reject(); 
} 
}); 

promise. 
    then(function () { 
        console.log('Success, You are a GEEK'); 
    }). 
    catch(function () { 
        console.log('Some error has occured'); 
    }); 

The above code works fine. But if I just execute the function that is passed as argument to Promise(),I get an error saying resolve is not a function.

(function(resolve, reject) { 
const x = "geeksforgeeks"; 
const y = "geeksforgeeks"
if(x === y) { 
  resolve(); 
} else { 
  reject(); 
} })()

if i run the above code, i get the below error

Uncaught TypeError: resolve is not a function

Can someone explain how this works?


Solution

  • resolve and reject come from Promise objects, but they aren't methods. The Promise constructor sort of looks like this:

    class Promise {
      // handler should look like (resolve, reject) => {}
      constructor(handler) {
        function resolve(value) { /***/ }
        function reject(err) { /***/ }
    
        handler(resolve, reject);
      }
    }
    

    When you call new Promise(handler) with a handler of type function, the handler gets called with two functions. When you call the same handler with no arguments, the handler tries to call undefined and that's why you see the TypeError.