I need to write some Cloud Functions in nodejs. This particular Cloud Function needs to iterate over an array of URLs and make some asynchronous calls to a third-party API.
Here is some placeholder code that simulates what I'm trying to do, adapted from here:
function checkPhotos(photos) {
var checkedPhotos = [];
var promiseArray = photos.map(asyncFunction);
Promise.all(promiseArray).then(results => {
console.log('results are: ', results)
results.forEach(result => { checkedPhotos.push(result) });
})
// I want to block here until the Promise.all call above completes
// but it does not block, it returns [] immediately while the async
// calls run
return checkedPhotos;
}
// This is a pretend async function to simulate the third party API
function asyncFunction(photo) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("in async function, photo is " + photo)
resolve(photo)
}, Math.random()*2000)
})
}
Then I call the functions:
var photos = ['https://example.com/example.jpg', 'https://example.com/example2.jpg'];
var checkedPhotos = checkPhotos(photos);
I expect checkedPhotos
to contain the values from results
but it is an empty array at first, then the asynchronous calls complete and the array gets populated. How do I make checkPhotos()
block until all the asynchronous calls are complete so I can return checkedPhotos
as a fully populated array?