Mohit Shah
Mohit Shah

Reputation: 862

Chaining in JavaScript Promises

I am going through a text book called Angular 2 Cookbook. In Chapter 4 there is a chaining Promises section which has the following code

const incr = val => { console.log(val); return ++val;};

var outerResolve;

const firstPromise = new Promise((resolve,reject) => { outerResolve = resolve;});

firstPromise.then(incr);

const secondPromise = firstPromise.then(incr);

const thirdPromise = secondPromise.then(incr);

outerResolve(0);

The output shown is

//0 0 0 1 1 2

//According to me output should be 0 0 1

Can someone please explain the result given in the book and the fault in my understanding of this vital concept?

Upvotes: 0

Views: 81

Answers (2)

Redu
Redu

Reputation: 26161

The code in the book would correctly log as;

0
0
0
1
1
2

However you haven't analysed the example in full. The snippet that you provide in your question is just half of it. The example code in the book is as follows;

const incr = val => { console.log(val); return ++val;};

var outerResolve;

const firstPromise = new Promise((resolve,reject) => { outerResolve = resolve;});

firstPromise.then(incr);

const secondPromise = firstPromise.then(incr);

const thirdPromise = secondPromise.then(incr);

outerResolve(0);

secondPromise.then(incr);
firstPromise.then(incr);
thirdPromise.then(incr);

Upvotes: 1

Mohit Shah
Mohit Shah

Reputation: 862

The output shown in the book's example is incorrect. The correct output is 0 0 1.

If the parent promise is resolved then it triggers the child promises to be resolved. So the following happens.

  1. The firstPromise should be resolved and its handlers (2 in this case) should be called outputting 0 and 0 since the handlers are not chained.

  2. Then secondPromise should be resolved and its handler should be called outputting 1.

  3. Then thirdPromise should be resolved and as it has no handlers nothing will be outputted.

Upvotes: 1

Related Questions