I've a Promise
array. While passing it to Promise.all
, it returns unusual response. Okay this is the minimal example of what I'm trying to achieve.
const promiseChain = [1, 2, 3].map(number => new Promise(resolve, reject) => {
// Calling an function with callback.
getMyObj(number, (err, myObj) => {
if (err) reject(err);
else {
// Comment 1
// Here I'm able to log the desired result both number & myObj.
resolve({ number, myObj });
}
})
});
Promise.all(promiseChain).then((results) => {
results.forEach(result => {
// Comment 2
// Here number is correct for all objects.
// But, myObj is same for all the numbers.
});
});
Check the comments. What I'm able to log in place of comments are as follows,
Comment 1:
{ number: 1, myObj: {a: 1}}
{ number: 2, myObj: {b: 2}}
{ number: 3, myObj: {c: 3}}
Comment 2:
{ number: 1, myObj: {c: 3}}
{ number: 2, myObj: {c: 3}}
{ number: 3, myObj: {c: 3}}
Here, What am I doing wrong and how I can fix this?
@mpm, first of all thanks much for your effort.
@HMR, dude thanks for the hint. Without it I'd have wasted several hours.
What I had to do to fix the issue was deep clone. I used lodash cloneDeep function to fix the issue. So, right below comment 1
doing the following fixed the issue.
resolve({ number, myObj: _.cloneDeep(myObj) });