I would expect the output for the following snippet to be 1, 2, 3, 4
. But, the actual output order is 1, 4, 3, 2
.
self.promiseChain = new Promise(function (resolve, reject) {
setTimeout(resolve, 4000);
}).then(function () {
console.log(1);
});
self.promiseChain.then(function () {
return new Promise(function (resolve, reject) {
setTimeout(resolve, 3000);
}).then(function () {
console.log(2);
});
});
self.promiseChain.then(function () {
return new Promise(function (resolve, reject) {
setTimeout(resolve, 2000);
}).then(function () {
console.log(3);
});
});
self.promiseChain.then(function () {
return new Promise(function (resolve, reject) {
setTimeout(resolve, 200);
}).then(function () {
console.log(4);
});
});
http://www.es6fiddle.net/imu5bhoj/
Everything I've read about promises indicates it should be possible to get the desired order in a 'flat' chain like this. Apparently I'm missing some detail? Could someone help point me in the right direction?
Here's a fiddle (http://www.es6fiddle.net/imu6vh1o/) for how to do it in a non-flat way, but it's harder to reason about and makes sequential chaining awkward.
I've searched similar issues on stack overflow but none of them answer the question generically using a straightforward example (that I could find).