Ninja420
Ninja420

Reputation: 3872

difference between two functions

What is the difference between these two functions written in javascript ?

function 1

var a, b;

this.get('obj').then(function(ob) {
    a = ob.get('prop');
}.bind(this)).then(function() {
    this.get('obj').reload();
}.bind(this)).then(function(){
    b = this.get('obj.prop')    
}.bind(this))

function 2

this.get('obj').then(function(ob) {
    a = ob.get('prop');
}.bind(this)).then(function(){
   this.get('obj').reload().then(function(){
       b = this.get('obj.prop');
   }.bind(this))
}.bind(this))

The first one is erroneous.

Upvotes: 1

Views: 71

Answers (1)

dfsq
dfsq

Reputation: 193271

I added some markers to your code for reference.

This is snippet #2:

this.get('obj').then(function(ob) { // #1
    a = ob.get('prop'); 
}.bind(this)).then(function() { // #2
   this.get('obj').reload().then(function() { // #3
       b = this.get('obj.prop'); 
   }.bind(this))
}.bind(this));

Now, the difference is that it's guarantied that callback #3 will be invoked after reload method completes, in other words - variable b will be initialized only after reload promise is resolved.

On the other hand in the first snippet, variable b gets initialized independently on the status of the reload promise.

Demo: here is a demo for you to visually see the difference http://jsfiddle.net/fn93gz3w/ (remove false && to run snippet).

And finally, you can make the first snippet behave the same as the second (properly) if you return new Promise from the second then block: in this case promises get chained and the third callback with b initialization will wait until reload resolves. Check this behavior in my demo.

Upvotes: 4

Related Questions