1

What I am doing :

function first()
{
   var array = [];
   for(int i=0; i<10; i++)
   {
      second(i/* to be processed*/).then((returnedObject) => 
      {
          array.push[returnedObject];
      });
   }
   return array;
}

but when the function first executes, it returns empty array.

I need help with a promise or something which will make sure that the array will be returned only after the for loop gets executed completely as well as the function second inside it returns data to be stored in the array.

prince47
  • 41
  • 5
  • 2
    Does this answer your question? [Asynchronous Process inside a javascript for loop](https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop) – Boaz Apr 12 '20 at 15:03

1 Answers1

0

Your second function returns a Promise which means it does the action asynchronously. In other words, the return value from second is not the returned object, but instead a promise to let you know when the returned object is ready. The .then function is going to get called with the result is ready, but you're not waiting for that.

There are a couple of ways to handle this but all mean that your top function (first) needs to act asynchronously also. Since second returns a Promise object, it's best if first carries on in that way too, so could look something like this:

function first() {
  const array = [];
  const promises = [];
  for(int i=0; i<10; i++)
  {
    promises.push(second(i/* to be processed*/).then((returnedObject) => 
    {
      array.push(returnedObject);
    }));
  }
  return Promise.all(promises).then(() => array);
}

This is collecting all of the promises returned by calls to second and then returns one Promise object itself that waits for all of the 10 promises to finish, then returns the array that's been constructed.

Note that this means first now returns a Promise too, and would have to be called in this way:

first().then(theArray => {
  // do something with the array
  console.log("array length:",theArray.length);  // should be 10
});

Another way is to use async/await which makes the code easier to follow:

async function first() {  // <-- declare the function as async
  const array = [];
  for(int i=0; i<10; i++)
  {
    // use 'await' to wait for second's returned object
    const returnedObject = await second(i/* to be processed*/);
    array.push(returnedObject);
  }
  return array;
}

Note that it still makes first return a Promise (as all async functions do) but it's much easier to follow.

Always Learning
  • 5,510
  • 2
  • 17
  • 34