Deski Rey
Deski Rey

Reputation: 131

Syntax of Promises in javascript is confusing

To access a method of the object we use dot operator like nameOfObject.nameOfMethod(). This is how I understand the dot operator.

This understanding of the dot operator is not helping me understand the syntax of promises in JavaScript. E.g see the code below:

var askMom = function () {
    willIGetNewPhone // calling the promise
        .then(function (fulfilled1) {
            // yay, you got a new phone
            console.log(fulfilled);
        })
        .then(function (fulfilled2) {
            // yay, you got a new phone
            console.log(fulfilled2);
        })
        .catch(function (error) {
            // ops, mom don't buy it
            console.log(error.message);
        });
}

It appears to me as if the code is saying - nameOfObject.thenMehtod().thenMethod().catchMethod();

How do I understand this? Does it mean it's normal in JavaSript to call methods of an object by using nameOfObject.method1().method2().method3;

Upvotes: 1

Views: 413

Answers (3)

Nishant
Nishant

Reputation: 21914

The basics is simple: a.function() takes an input and gives an output; the output could be any JavaScript object.

Now, what if a.function() returns something that is just like a? Now you can just continue forever. It's called chaining - a simple but powerful idea.

In the case of promise, then just registers a function that gets called with the promise's resolved value. To make chaining possible, it also returns a promise that gets resolved with the function you supplied to then. If you aren't getting the idea, just read up further on promises, it will sink in.

Hope this small snippet using the arrow function syntax can help you:

// getting the "resolver" to play around with
a = new Promise(_resolver_ => {resolver = _resolver_;});
// registering a "then"
b = a.then(result => {return result + 1;});
// resolving a
resolver(1);

Upvotes: 1

afenster
afenster

Reputation: 3608

This particular usage (promise.then(...).then(...)) looks similar but has nothing to do with your example object.method1().method2().method3(). In the former case (promise.then()) the result of each subsequent .then() is a new Promise. In the latter case, all methods normally return the same object, which makes it possible to do chaining, one example of it is EventEmitter:

eventEmitter
  .on('event1', func1)
  .on('event2', func2);

Here, each .on() returns the same instance so this kind of method chaining is possible. To make this chaining, each method (on in the above example) should return the current instance (this).

Upvotes: 1

Brad
Brad

Reputation: 163240

When you call .then(), you're executing a function just like any other. It then returns a promise that also can have .then() or .catch() called on it.

This is commonly referred to "chaining".

Upvotes: 2

Related Questions