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.