Skip to content

Instantly share code, notes, and snippets.

@co3moz
Last active April 5, 2016 16:34
Show Gist options
  • Save co3moz/0fc4694c84da16db34c4 to your computer and use it in GitHub Desktop.
Save co3moz/0fc4694c84da16db34c4 to your computer and use it in GitHub Desktop.
Async Array Iterator
Array.prototype.iterate = function (cb, done, timeout) {
((timeout != undefined) || (typeof timeout == "object") || (timeout = 5000));
var total = this.length;
var result = [];
if (total == 0) {
return done(null, result);
}
var sent = false;
this.forEach(function (e, i) {
setTimeout(function () {
cb(e, function (data) {
if (data instanceof Error) {
if (!sent) {
done(data, null);
sent = true;
}
} else {
result[i] = data;
if (--total == 0 && !sent) {
done(null, result);
sent = true;
}
}
})
});
});
if (timeout != null) {
setTimeout(function () {
if (total != 0 && !sent) {
done(Error("timeout"), null);
sent = true;
}
}, timeout);
}
};
@co3moz
Copy link
Author

co3moz commented Apr 4, 2016

error example

[1, 2, 3].iterate(function(i, done) {
  if(i == 2) {
    done(Error("something bad happened!"));
  } else {
    done(i);
  }
}, function(err, results) {
  console.log(err, results); // err = something bad.., results = empty
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment