I'm trying to understand why the following results happen. I bet there's something to do with the event loop and the fact that all sync code runs before async code, but I cannot apply that knowledge to this example.
// const axios = require('axios');
const array = [1, 2, 3];
const user = {};
const promises = array.map(async (item) => {
console.log('start');
user['id'] = item;
const responseUser = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${user.id}`
);
console.log('middle');
const responseUser2 = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${user.id}`
);
console.log('end result 2: ', responseUser2.data.id);
console.log('end result: ', responseUser.data.id);
});
Promise.all(promises);
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
Results:
start
start
start
middle
middle
middle
end result 2: 3
end result: 3
end result 2: 3
end result: 2
end result 2: 3
end result: 1
userand mutate it this way without some kind of mutex or lock because it produces a race condition.Promisesdon't run JavaScript in parallel (though if they run internal host code, like for network IO, then that code in the host could run in parallel, but JS code itself will not). So you don't need any kind of locking to be thread-safe - though in this case, yes, mutatinguser['id']is wrong, but it isn't a race-condition (specifically) in this context.awaittoPromise.all(promises);, so change your code toawait Promise.all(promises);mapwithout areturn? Use aforloop.await/asyncbehaves similar to cooperative multitasking. So as soon as you useawait(or callbacks) the sequence and timing of the execution can change, and that can lead to race conditions. (For sure not that variables are modified by to cores at the same moment, but that’s not the requirement for a race condition)