ffxsam
ffxsam

Reputation: 27713

ES6 - Confused about processing order of Promise

I've got this code:

let p1 = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve({dogs: ['Fido', 'Spot']});
    }, 2000);
});

p1.then(function (val) {
    console.log('first then');
    console.dir(val);
    return _.extend(val, {cats: ['Fluffy', 'Whiskers']});
}).then(function (val) {
    console.log('second then');
    console.dir(val);
});

The unexpected console output shows:

enter image description here

I don't understand how cats could possibly be part of the value before it's actually appended into the object. The results printed in the second then make sense to me though. Am I missing something?

Upvotes: 1

Views: 56

Answers (2)

inf3rno
inf3rno

Reputation: 26129

As far as I know there is a bug in console.log by ES6 Promises. It waits for a few seconds before it logs the value of your object, that's why it contains the cats. If I remember well, this bug happens in firefox. I don't know how it behaves by the other browsers.

Upvotes: 0

SLaks
SLaks

Reputation: 887315

You're adding the cats property to the same object you already logged.

As the i icon tells you, the console only reads the properties of the object when you actually expand it.

Upvotes: 1

Related Questions