Skip to content Skip to sidebar Skip to footer

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 help

Solution 1:

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".

Solution 2:

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).

Solution 3:

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 = newPromise(_resolver_ => {resolver = _resolver_;});
// registering a "then"
b = a.then(result => {return result + 1;});
// resolving aresolver(1);

Post a Comment for "Syntax Of Promises In Javascript Is Confusing"