Unexpected promise instead of array

I’m working with node and mongo. I’m trying to run a series of parallel requests using a netlify serverless function which I’m trying to create build using mongo records. So far I have:

paralellNum = 2;

const filter = { 'Parcel': { $regex: '[0-9]' }, 'UseCode': { $exists: false } };
let records = await collection.find(filter).limit(firstNum).toArray()
console.log('number of records selected from db: ', records.length);

const fetchURL = (obj) => fetch('http://localhost:8888/.netlify/functions/meta1', {
  method: 'POST',
  body: JSON.stringify(obj),
  headers: { 'Content-Type': 'application/json' }
});

  let outputArray = [];
  for (let i = 0; i < (paralellNum-1); i++) {
    const record  = records.pop();
    const obj = {"_id":record._id,"apn":record.Parcel};
    outputArray.push(fetchURL(obj));
  } 

  console.log(outputArray);

I was expecting the output array to contain the constructed fetch requests, but instead I’m seeing:

1) [Promise]
0:
Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined, 
Symbol(async_id_symbol): 59, Symbol(trigger_async_id_symbol): 58}
length:1

Whay am I getting a promise instead of the expected array?

>Solution :

You can wait for all the Promises to finish with Promise.all.

Promise.all(outputArray).then(result => {
    console.log(result);
    // use result here
});

Leave a Reply