Skip to content

Instantly share code, notes, and snippets.

@Semigradsky
Created March 26, 2017 10:54
Show Gist options
  • Save Semigradsky/4f10f4b996fbc7fcfb445f2cdde68b9e to your computer and use it in GitHub Desktop.
Save Semigradsky/4f10f4b996fbc7fcfb445f2cdde68b9e to your computer and use it in GitHub Desktop.
cancellable async
asyncTasks.prototype.map = function (items, fn, done) {
var that = this,
identity = this.identity;
async.map(
items,
function (item, done) {
fn(item, function (err, item) {
if (identity !== that.identity) {
done(Error(PREMATURE_EXIT));
return;
}
if (err) {
done(err);
return;
}
done(null, item);
});
},
function (err, items) {
if (err && err.message === PREMATURE_EXIT) {
return;
}
done(err, items);
}
);
};
asyncTasks.prototype.do = function (asyncFn, callback) {
var identity = this.identity,
that = this;
asyncFn(function (...args) {
if (identity !== that.identity) {
return;
}
callback(...args);
});
};
function Collection(options) {
this.index = options.index || 'id';
this.format = options.format;
this.data = [];
this.indexes = {};
this.asyncTasks = new AsyncTasks();
}
var model = new Collection({
format: () => ({})
});
// model.init(trips.getAll, domains.api.intercept(presenter.render));
Collection.init(initFn, done) {
var that = this;
this.clear();
if (!initFn) {
return;
}
this.asyncTasks.do(initFn, function (err, items) {
if (err) {
done(err);
return;
}
that.indexes = items.reduce(function (obj, item) {
obj[item] = true;
return obj;
}, {});
if (that.format) {
if (that.format.length === 1) {
that.data = items.map(that.format);
done(null, that.data);
}
that.asyncTasks.map(
items,
that.format,
function (err, items) {
if (err) {
done(err);
return;
}
that.data = items;
done(null, that.data);
}
);
} else {
that.data = items;
done(null, that.data);
}
});
}
Collection.clear() {
this.data = [];
this.indexes = {};
this.asyncTasks.cancel();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment