Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@soarez
Forked from tdantas/question.js
Created October 28, 2012 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soarez/3969739 to your computer and use it in GitHub Desktop.
Save soarez/3969739 to your computer and use it in GitHub Desktop.
programming async trick.
//Question:
// Environment: NodeJS
// Lets suppose that you have a collection of items, and your function must persist all items using the
//database.insert(item, callback ) function. When you finish the task, you should call the callback function.
// If one item raise a error, the callback(err) must be called and never call the callback anymore.
function noop() {}
function saveBulk(items, callback) {
var completed = 0;
items.forEach(function(item) {
database.insert(item, function(err) {
if (err) {
callback(err);
callback = noop;
return;
}
if (++completed == items.length)
callback(null);
});
});
}
saveBulk([ {name:"thiago"}, {name: "r42"}, { name: "rulio"} , { name: "nodejs"} ], function(err) {
console.log("Ok");
});
//Question:
// Environment: NodeJS
// Lets suppose that you have a collection of items, and your function must persist all items using the
//database.insert(item, callback ) function. When you finish the task, you should call the callback function.
// If one item raise a error, the callback(err) must be called and never call the callback anymore.
function saveBulk(items, callback) {
// Your code here
}
saveBulk([ {name:"thiago"}, {name: "r42"}, { name: "rulio"} , { name: "nodejs"} ], function(err) {
console.log("Ok");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment