Search code examples
javascriptecmascript-6promisees6-promise

Understanding the Promise Constructor in JavaScript


Here's a code snippet from MDN Promise page.

let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code. 
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout( function() {
    resolve("Success!")  // Yay! Everything went well!
  }, 250) 
}) 

In above code, I don't understand where is the function definition of resolve (and reject)? Here we are simply passing resolve as a parameter to the Promise constructor, and later calling it when we do resolve("Success!"), so where exactly is resolve defined?


Solution

  • Multiple parts to this, first this is an arrow function so:

    (resolve, reject) => {}
    

    is short-hand for (and some other stuff around this, etc):

    function(resolve, reject){}
    

    So you're passing a function as a parameter into the other function. Functions are objects in JavaScript. So if you imagine the implementation of Promise it might look something like this (not the actual implementation):

    Promise(callBackFunction){
        ...//do some things
        callBackFunction(resolve, reject); 
    }
    

    So, callBackFunction is the function you have passed in using the arrow function and when promise gets to the relevant point in the code, it will call your function and pass it resolve, reject. resolve and reject are also function objects here.

    so where exactly is resolve defined

    Inside the Promise code.