I have been working with JavaScript promises recently and came across the following situation that got me thinking:
var combinedArray = [];
function getArrayOne() {
$http.post(arrayOnePath).then(function(arr) {
combinedArray = combinedArray.concat(arr);
}) // More code preventing me from using Promise.all(...)
}
function getArrayTwo() {
$http.post(arrayTwoPath).then(function(arr) {
combinedArray = combinedArray.concat(arr);
}) // More code preventing me from using Promise.all(...)
}
function getAllArrays() {
getArrayOne();
getArrayTwo();
}
While I was writing this logic it dawned on me that there could be a potential race condition if both promises resolve at the same time (as they access a shared resource). After thinking about this for a little while longer I realized that the then(..)
resolutions are executing after the post returns which means this code is running in JavaScript's synchronous execution environment.
Could someone please provide some clarity for me on whether the two combinedArray.concat(arr);
statements could cause a problem if both promises resolve at the same time?
[Edit]
Following some of the comments I just want to add that I don't mind what order the arrays are concatenated into combinedArray
.