Home > database >  Updating external objects/variables within async Promise.all
Updating external objects/variables within async Promise.all

Time:10-20

When updating values within a Promise.all(), are the following results guaranteed? My understanding is that the internal function would be happening in parallel, but how would that affect the result?

  • a will be 6 (0 1 2 3)
  • b will have length 8 (length of d * 2)
    • order is not guaranteed
  • c will have length 3 and all the key/value pairs are guaranteed except for c['a']
const networkCall = async () => {
  // takes time
}

const update = async (i) => {
  let a = 0;
  let b = [];
  let c = {};

  const d = ['a', 'b', 'c', 'a'];
  
  await Promise.all(d.map(async (i, index) => {
    await networkCall();
    a  = index;
    b.push(i);
    b = [i, ...b]
    c[i] = index;
  });

  console.log(a);
  console.log(b);
  console.log(c);
}

update()

I looked through similar questions but didn't find a satisfactory answer.

CodePudding user response:

When updating values within a Promise.all()...

Promise.all is unrelated to updating the values of a, b and c. Promise.all will just take an array of promises and create a new promise. That's it. That new promise is returned before any asynchronous code has executed. It doesn't influence how some callback function is making updates. The promise retured by Promise.all is used here to make sure the console.log calls are only made when all asynchronous code has executed.

My understanding is that the internal function would be happening in parallel,

"Parallel" could have different meanings... It is not that each statement separately could run in round-robin with another one. In this particular case it is guaranteed that for a given index, the four statements below the await are executed as one uninterrupted block without any other JavaScript running. Only when that block is completed (and the callback returns) can there be a possibility to have the same block executed for another execution context of that block (with a different index variable and value).

a will be 6 (0 1 2 3)

Yes, this is guaranteed when console.log(a) is executed, even though it could for instance have been calculated as 1 0 3 2.

b will have length 8 (length of d * 2) -- order is not guaranteed

Yes. Order is not guaranteed, but the array is guaranteed to be a "palindrome": b[i] === b.at(-i-1)

c will have length 3 and all the key/value pairs are guaranteed except for c['a']

Yes.

  • Related