I encountered a piece of code that left me puzzled about the flow of execution.
var x = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([1, 2, 3]);
}, 0);
});
};
x().then((val) => {
console.log(val);
}).catch((err) => {
console.log(err.message);
});
console.log("hello");
for (var i = 0; i < 10; i++) {
console.log(i);
}
var y = Promise.all([Promise.resolve(1), Promise.reject(Error("err"))]);
y.then((arr) => {
console.log(arr);
})
.catch((err) => {
console.log(err);
});
Promise.resolve('ta-da!')
.then((result) => {
console.log('Step 2 received ' + result);
return 'Greetings from step 2';
})
.then((result) => {
console.log('Step 3 received ' + result);
})
.then((result) => {
console.log('Step 4 received ' + result);
return Promise.resolve('fulfilled value');
})
.then((result) => {
console.log('Step 5 received ' + result);
return Promise.resolve();
})
.then((result) => {
console.log('Step 6 received ' + result);
});
Below are the sequence of logs:
"hello"
0
1
2
3
4
5
6
7
8
9
"Step 2 received ta-da!"
"Step 3 received Greetings from step 2"
"err"
"Step 4 received undefined"
"Step 5 received fulfilled value"
"Step 6 received undefined"
[1, 2, 3]
The for loop behaves as expected. The setTimeout() operates as intended, and the promise resolves after the event loop.
The two other promises seem to clash, causing unexpected results. I anticipated the synchronous fulfillment of promises, leading to the following expected results:
"hello"
0
1
2
3
4
5
6
7
8
9
"err"
"Step 2 received ta-da!"
"Step 3 received Greetings from step 2"
"Step 4 received undefined"
"Step 5 received fulfilled value"
"Step 6 received undefined"
[1, 2, 3].
Although promises are resolved asynchronously, it's puzzling why they collide.
Refer to the attached screenshot.