Edit:
I was a bit confused originally, and copy & pasted something I wrote for slack. Sorry about that.
Like @Bergi said, if you need an array of Promises from an array of objects
then it's usually better to transform that existing array using .map()
. As mentioned, this looks like:
const getPromises = (objects) => {
return objects.map(object => new Parse.Promise.as()
.then(() => {
return destroy(object);
})
);
}
// No 'temp' array needed, and most important: promise variables aren't 'lost'
// Then you can similarly use this pattern:
return Parse.Promise.when(getPromises(objects));
// Or this:
return Promise.all(getPromises(objects));
My original answer (below) was a bit ambiguous on its own, hopefully my answer above gives it more context. :)
I avoid using for
loops or Array.forEach
. When I discovered .forEach()
I used it for everything, assuming it was the answer to my for loops
mess. I've come to learn both are a code-smell 99.99% of the time. Reason: They typically necessitate temp arrays, and make nested loops really awkward.
While .map()
largely solves this when your arrays are same size, 1:1 or 20:20, other Array
methods are useful for asymmetric transforms, 20:1 (for example: totaling the cost of 20 products into 1 number, or finding the largest transaction in the list):
.map - use for 1:1 array transforms, as @bergi suggests.
.reduce - useful for transforming 1 array into ANYTHING else. Need a sum or subtotal? Or results grouped by day? Use .reduce().
.filter - return only items which result in a `true` result
.find - use to avoid full array scans when only 1 item must be returned.
.some - exit array scan returning true at first opportunity
let downloadedMsgs = emails.map(m => downloadBody(m))
let recipientsCount = emails.reduce((count, m) => count + m.to.length, 0)
let onlyRecentMsgs = emails.filter(m => m.isNew)
let aRecentMsg = emails.find(m => m.isNew)
let hasNewMessage = emails.some(m => m.isNew)
// (Notice last 3 identical predicate fn's with different uses: aka pluripotency)
The other issue in the code is the risk of losing your Promises! This is important, if you ever might have dozens or 100's of objects in your array, triggering an HTTP request in the loop would be pretty unreliable (eventually you'd exhaust available sockets). The best way to throttle this involves returning your Promises.