Silent Promise Bug
Demonstrate how a possible bug can occur if promises are not handled correctly.
by Nicolas Mancilla
JavaScript
function asyncFn() {
return new Promise((resolve) => {
setTimeout(resolve, 1000, 'value ' + Math.random());
});
}
function exec() {
const arr = [];
return new Promise(() => {
for (let i = 0; i < 3; i++) {
console.log('Iteration:', (i + 1));
asyncFn().then((data) => {
console.log('Resolved data:', data);
arr.push(data);
});
}
console.log('After upload:', arr);
}).then(() => {
console.log('Second step:', arr);
}).catch(e => console.error);
}
exec();