yaoxing
yaoxing

Reputation: 4203

execute a function against array items in sequence

Say I have an array and a function A:

var array = ['a', 'b', 'c'];
function A(p) { ... };

now I want to pass each item of array to function A, and want them to be executed in a sequential order. usually there won't be any problem. I can do:

array.forEach(function(item) {
  A(item);
}

however, if there are some asynchronous action in A, everything becomes messed up. so the question is:

How can I have them executed orderly even if there are asynchronous actions in A?

By which I mean, I want A('b') to be executed after A('a') is completely finished (including all the asynchronous actions in there).

I guess there must have been some utilities doing such things already. can someone shed me some light?

Upvotes: 2

Views: 523

Answers (3)

shut up and stand up
shut up and stand up

Reputation: 13

var array = ['a', 'b', 'c'],i = 0;
var A = function(p){
    //some code
    $.ajax({
        success:function(){
            try{
                A(item[++i]);
            }catch{
                return;
            }
        }
    });
}

Are you mean to this?

Upvotes: 0

Amit
Amit

Reputation: 46341

JavaScript Promises allow you to do just that.

This example is pretty convoluted, but it shows some aspects of using Promises:

var arr = ['a', 'b', 'c'];

function processAsync(val) {
  return new Promise(function(res, rej) {
    console.log("Starting:", val);
    setTimeout(function () {
      console.log("Done:", val);
      res();
    }, 1000);
  });
}

arr.reduce(function(promise, i) {
  return promise.then(processAsync.bind(null, i));
}, Promise.resolve());

Upvotes: 3

thomas
thomas

Reputation: 2578

This is a perfect use case for "eachSeries" from async.js

You could use it this way

async.eachSeries(array, A, function(err) {
    // this function gets called at the end 
    // after your array has been looped
});

And you would have to modify your A function with a second parameter - a callback.

function A(p, callback) {
    // ...
    return callback();
}

That calls the callback parameter once your async calls in A are finished.

Upvotes: 6

Related Questions