While messing with JavaScript Promises, I noticed a strange thing: if to return a new Promise inside a callback of a then-statement, such a then-statement seems to pass to the next "then" NOT this new Promise, but the result of the latter being resolved! An example:
new Promise(resolve => { resolve() })
.then(() => {
return new Promise(resolve => {
setTimeout(() => {
resolve(1);
}, 1000);
})
})
.then(x => {
console.log(typeof x, x);
return new Promise(resolve => {
setTimeout(() => {
resolve(2);
}, 1000);
})
})
.then(x => {
console.log(typeof x, x);
return new Promise(resolve => {
setTimeout(() => {
resolve(3);
}, 1000);
})
})
.then(x => {
console.log(typeof x, x);
})
What I get in the console after this, is:
number 1
number 2
number 3
, which is definitely NOT what I expected, as I know that a then-statement's callbacks should accept a return value of a previous then statement's callback – so I expected to see in the console objects (Promises) instead of numbers... Did I miss something?