Iterating over a collection result one-by-one

How can i run a forEach on a collection but only move to the next item when the current item has finished being processed. Does meteor collection cursor have a next() feature? There is no sequential index to my collection so I cannot make new queries based on an Index.


Images.find( {} ).forEach( function(image){
   downloadImage( image.url, function(){
        next();  now that the downloadImage has returned, move on to the next image in the forEach 
   } )

Sorry don’t have code example, but maybe you can do a .fetch() on the Image collection, then iterate over the returned array.

Your downloadImage function may have to be a promise so you can let each image finish downloading and then proceed to the next one.

1 Like

You don’t say whether you need this on the client or the server.

If it’s on the server, your requirement is satisfied using standard Meteor “sync-style” coding - as long as you use Meteor’s HTTP package* for your downloading (the non-callback form).

Promises (and async/await) seem to be a good alternative, but I don’t believe will address your requirement directly. So, if you need this on the client or want to use Promises on the server you will need to use something like promise-waterfall.

* or wrap a 3rd party function with Meteor.wrapAsync or Meteor.bindEnvironment.