1

I have a list of items, which I want to run an async task on each.

I want to synchronize so each element will be processed once the preceding element has completed. What I've tried so far is:

function processItems(items) {
    var i = 0;
    while(i < items.length) {
      asyncFunc(items[i], function() { i++ }); // asyncFunc takes a callback parameter       
    }
}

However this loops forever (I believe i is out of scope in the callback function).

Is there a better way to achieve this?

2 Answers 2

6

I think the following accomplishes what you're looking for:

function processItems(items) {
    var i = 0,
        length = items.length,
        fn = function() {
            if(i < length) {
                asyncFunc(items[i], fn);
                i++;
            }
        };

    fn();
}

fn is a function that sets the callback equal to itself as long as the index is less than the length. Then I call fn once to start it off. Here's a fiddle:

http://jsfiddle.net/8A8CG/


Alternatively, if asyncFunc returns a promise, you can use Array#reduce to process the items in a series:

function processItems(items) {
  return items.reduce((promise, item) => {
    return promise.then(() => asyncFunc(item));
  }, Promise.resolve());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worked a treat, nice example of solving with recursion being simpler than an iterative method
1

If you need to execute a set of async function in series, I highly recommend the async module for node. It offers a series method to execute async tasks in series. It also offers a waterfall method that will pass the results of the previous task to the next task.

Oops. You are looking for eachSeries. Here's how it might work for you:

var async = require('async');

async.eachSeries(items, asyncFunc, function(err){ if(err) return "OH NO"; return "Yay!"})

Make sure asyncFunc invokes a callback with either an error or null.

2 Comments

Looking at the series example, how would this translate to my problem of iterating over the array and calling an async on each one in succession?
@ioseph I modified my answer to the demonstrate the appropriate use of the async library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.