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?
CodePudding user response:
You can wait for all the Promises to finish with Promise.all
.
Promise.all(outputArray).then(result => {
console.log(result);
// use result here
});
CodePudding user response:
fetch
returns a promise for the request. If you want the response of the requests to be in your outputArray
you need to change outputArray.push(fetchURL(obj));
to fetchUrl(obj).then(response => outputArray.push(response));
This waits for the fetch call to finish and then takes the response and puts it into your array.