Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading