I have the follow code below:
var arr = [
{ condition: true, recursion: [], result: 'OLD_RESULT', recursiveArray: [{condition: true, result: 'OLD_RESULT'}] },
{condition: false, result: 'OLD_RESULT'},
{ condition: true, recursion: [], result: 'OLD_RESULT', recursiveArray: [{condition: true, result: 'OLD_RESULT'}] },
{condition: false, result: 'OLD_RESULT'},
];
var someAsyncCall = async () => {
return 'NEW VALUE';
};
var asyncInMap = (arr) => {
return arr.map(async (elem) => {
const condition = elem.condition;
if (condition) {
const result = await someAsyncCall();
elem.result = result;
}
if (elem.recursiveArray) {
elem.recursion = asyncInMap(elem.recursiveArray);
}
console.log('SECOND:', elem);
return elem;
});
};
console.log('FIRST');
var promisesVal = asyncInMap(arr);
console.log('THIRD');
var completedVal = await Promise.all(promisesVal);
console.log('FOURTH', completedVal);
My question is in the order of the console.log's
I am getting:
FIRST
SECOND: {condition: false, result: "OLD_RESULT"}
SECOND: {condition: false, result: "OLD_RESULT"}
THIRD
SECOND: {condition: true, recursion: Array(1), result: "NEW VALUE", recursiveArray: Array(1)}
SECOND: {condition: true, recursion: Array(1), result: "NEW VALUE", recursiveArray: Array(1)}
SECOND: {condition: true, result: "NEW VALUE"}
SECOND: {condition: true, result: "NEW VALUE"}
FOURTH (4) [{…}, {…}, {…}, {…}]
Why is the Third
log being printed before all the Second
console.log
are done? Is this because I am using recursion inside of the asyncInMap
function along with async/await
? Ideally the asyncInMap
should be completed (with all the Second
logs printed first) and then only the Third
log should be printed correct?