12

I have begun learning javascript promises. But I just can't understand the concept of promises. The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

See this example of Promise:

function getImage(url){
    return new Promise(function(resolve, reject){
        var img = new Image()
        img.onload = function(){
            resolve(url)
        }
        img.onerror = function(){
            reject(url)
        }
        img.src = url
    })
}

Now who does pass resolve and reject methods, as my understanding of javascript says to me that this script will throw unknown variable errors as resolve and rejects are not defined?

getImage('doggy.jpg').then(function(successurl){
    document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).catch(function(errorurl){
    console.log('Error loading ' + errorurl)
})

Now you see a method like the above, the only way these methods(resolve and reject) are passed are via then and catch as used in above method call to getImage.

Joshua Dance
  • 8,847
  • 4
  • 67
  • 72
user3769778
  • 967
  • 2
  • 7
  • 26
  • `resolve` and `reject` are parameters of the function you pass into the `Promise`. The `Promise` itself calls this functions and passes in the two parameters. – Xaver Kapeller Oct 14 '16 at 15:22
  • 2
    Compare: `function cb(resolve, reject) { ... }; new Promise(cb);` – does that help…? – deceze Oct 14 '16 at 15:23
  • @deceze It did helped me out, but one things I am still confused about , then why "then" and "catch" are used to pass other methods ? They work as if the methods pass in them are resolve and reject methods ? – user3769778 Oct 14 '16 at 15:33
  • 1
    Yes, instead of calling `resolve`, which then calls your `then` callback, you could just directly call your `then` callback. It's essentially the same thing. **However**, promises enable you to *compose* (chain) such callbacks in ways that would quickly become very complicated if you just call callbacks directly. *Especially* if you figure in the complexity of error handling, which promises solve very easily with chainable `catch` callbacks. – deceze Oct 14 '16 at 15:39

6 Answers6

8

The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

Nobody.

The functions are passed by the promise constructor.

They are passed to the function which you pass as the first argument to the promise constructor.

Nipuna Saranga
  • 970
  • 13
  • 18
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • so why do we pass variables to resolve and reject methods: `resolve(url)` This variables can be anything, passing variable from outer scope makes no sense as the method is system generated and can be anything. – user3769778 Oct 14 '16 at 15:36
  • 1
    The resolver and rejecter function pass the variables on to `then` functions, but which not generated by the Promise API. – Quentin Oct 14 '16 at 15:41
8

The Promise constructor is initialized with a callback, and the constructor passes reject and resolve as parameters when the callback is called.

Here is a simple demo:

class PromiseDemo {
  constructor(cb) {
    cb(this.resolve.bind(this), this.reject.bind(this));
  }
  
  resolve(d) {
    console.log('resolve', d);
  }
  
  reject(d) {
    console.log('reject', d);
  }
}

new PromiseDemo((resolve, reject) => {
  Math.random() > 0.5 ? resolve('1') : reject('1');
});
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • So, the only reason `resolve` and `reject` are parameters is to bind `this` to the `Promise` object? Why is this binding necessary? – AlwaysLearning Jul 12 '21 at 12:45
  • The resolve and reject are passed as callbacks, they lose the reference to `this`. If you'll want to use `this` inside resolve/reject you'll need to bind them. In the example `this` is not used in any of them, so you can skip the binding. – Ori Drori Jul 12 '21 at 12:50
  • My question is really the following. Since `resolve` and `reject` are built-in functions, why make the call-back function accept them as arguments? It was possible for the call-back function to simply call them as any other built-in function... – AlwaysLearning Jul 12 '21 at 16:22
3

I had the same problem in understanding Promises.You need to look at the process of promise creation carefully. when you write var promise= new Promise(function(resolve,reject){...})

you are actually invoking constructor of Promise class or creating an object of Promise class. Now Promise constructor requires a function callback. Now resolve and reject are just function arguments and not any other values. You can write anything in place of resolve or reject like resolveHandler or rejectHandler.

These resolve or reject are nothing but the function callback that Promise calls when Promise is executed.

Now resolve is called when Promise is executed successfully and reject is called when promise is executed with some error or unsuccessfully .

The argument with which resolve is called can be accessed inside then like this

getImage().then(function(valueSentInResolve){ console.log('')})

The argument with which reject is called can be accessed inside catch like this

getImage().then(function(valueSentInResolve)
  {//..do something}
).catch(function(errorSentInReject){
  console.log('error',errorSentInReject )
})

I hope that helps.Let me know if I said anything wrong.

picmate 涅
  • 3,951
  • 5
  • 43
  • 52
Rishabh Nigam
  • 223
  • 3
  • 10
1

I have been studying Promises all day, and had the same question. I finally figured it out.

When you make a Promise object, you give the Promise Constructor an executor, which can be any function, as long as it has this signature.

anyFunction(resolutionFunction, rejectionFunction){
    // typically, some asynchronous operation.
}

So any function with 2 functions as the arguments can be used. The first function is what you call when it works, the second is what you call when it breaks. You can name those functions whatever you want as well.

The Promise Constructor takes the function you pass in and does a few things with it.

  1. It takes those 2 function arguments and generates a corresponding pair of functions that are "connected" to the Promise object.
  2. It runs the executor
  3. It ignores any return value from your executor

Now in your executor function when the promise resolves you call the positionally first function and pass it one value. It will look something like:

resolutionFunction(value)

You may be wondering, where is resolutionFunction defined? Remember the Promise Constructor defined that function for us. So we can call resolutionFunction without having to define it ourselves. Behind the scenes, when we call that resolutionFunction generated by the Promise Constructor, it sets the state of the promise to fulfilled, calls the function inside the promiseObject.then function, and passes the value into the .then function so you can use it.

You would call the 2nd positional function if the promise failed and the same things would happen and you could deal with the failure.

This Mozilla Doc on the Promise Constructor was very helpful.

Here is a short examples that shows what I explained above.

function anyFunction(callThisFunctionWhenItWorks, callThisFunctionWhenItBreaks) {
  let importantNumber = 10; //change to 11 if you want the promise to reject
  if (importantNumber == 10) {
    callThisFunctionWhenItWorks('Hooray, success, so we call resolved for the promise.');
  } else {
    callThisFunctionWhenItBreaks('Boo, rejected because important number is not equal to 10');
  }
}

//make a new promise
const examplePromise = new Promise(anyFunction);

//use the promise
examplePromise.then(function(result) {
  console.log(result);
}).catch(function (error) {
  console.log(error);
})
Joshua Dance
  • 8,847
  • 4
  • 67
  • 72
0

The promise library creates and passes those functions, along with all the other metadata needed to track the promise and record completion, store state and progress, cancel it, etc.

The folks behind Bluebird have published some info on how the library works internally, and you can see more in the Bluebird source.

ssube
  • 47,010
  • 7
  • 103
  • 140
0

does this make sense? This explanation could be completely incorrect!!

We provide the logic which should run asynchronously. The logic should accept 2 functions, resolve and reject. The reference of these functions is provided by Promise. These functions should be called by our logic when we have the final value or error. The Promise created initially is in Pending state. Calling resolve and reject changes the state to Fulfilled or Rejected respectively.

executeFunction(res,rej) = {
 do some op, say DB query. 
 if (success) res(value) //executeFunction uses the resolving functions to change state of the Promise. Calling res fulfills the promise with value
 if (fail) rej(reason)//executeFunction uses the resolving functions to change state of the Promise. Calling rej rejects the promise with reason
}

Rather than calling executeFunction directly (which would make the call synchronous), we create a Promise will will run the executeFunction code in a separate thread (asynchronously) let p = Promise(executeFunction(res,rej));. We get back a reference of the Promise.

My guess is that internally in the Promise, the following happens

Promise(e(res,rej)) = { 

// the Promise's constructor creates a new promise, initially in the pending state. It calls `e` (the executeFunction function) and provides references to the resolving functions to it that can be used to change its state.
  state = pending;
  e(_res,_rej); //starts my op. asynchronously (a new thread). Reference to resolving functions, _res, _rej is provided. _res and _rej are Promise's internal functions (see below)
  //constructor doesn't return till the async thread finishes
}

_res (value){ //Promise's internal method
 //probably sets the state of promise to Fulfilled and store the result of the Promise
 state = fulfilled
 resolvedValue = value;
}

_rej {//Promise's internal method
 probably sets the state of promise to Rejected and store the result of the Promise
 state = rejected
 resolvedValue = error;
}

Creating the Promise starts the execution of the code asynchronously. Now we are interested in knowing what is the result of executeFunction (we don't care when executeFunction finishes). To do this, we call then of the Promise p. then takes two optional arguments and registers them as callbacks. I am not sure when and who calls these callbacks. I know that then returns another Promise but I am not able to understand how that works

   then(executeFnIfPromiseResolved, executeFnIfPromiseRejected):Promise {
      register executeFnIfPromiseResolved as callback 
      register executeFnIfPromiseRejected as callback
      //NOT SURE WHO AND WHEN THE CALLBACKS ARE CALLED
      //then needs to return Promise. What would be the executor function of that Promise?
}
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • "*Promise will run the executeFunction code in a separate thread (asynchronously)*" - no, this has nothing to do with multithreading. In fact it's not even asynchronous, the `new Promise` constructor [calls the executor callback synchronously](https://stackoverflow.com/a/29964540/1048572). The asynchronous thing is started by the code in there, e.g. when calling `setTimeout`. – Bergi Dec 18 '18 at 19:33
  • Otherwise, [this explanation looks good](https://stackoverflow.com/a/50413998/1048572) – Bergi Dec 18 '18 at 19:34
  • Thanks. Could you please help me understand the purpose of `then` and how it works, particularly, who and how the callbacks are called? – Manu Chadha Dec 18 '18 at 20:30
  • The callbacks are scheduled when the state of the promise changes (or when `then` is called on a promise that is already settled). Who is calling them? The event loop - that part is natively asynchronous. – Bergi Dec 18 '18 at 20:34