I have the following code example.
var Promise = require('bluebird');
var model = function (object) {
this.name = object.name;
};
model.prototype.download = function () {
var self = this;
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, Math.random() * 100)
});
};
model.prototype.process = function () {
var self = this;
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('processed: ', self.name);
resolve();
}, Math.random() * 100)
});
};
var models = [new model({
name: 'user',
requires: ['company']
}), new model({
name: 'address',
requires: ['user', 'company']
}), new model({
name: 'company'
})];
Promise.map(models, function (model) {
return model.download()
.then(function () {
return model.process();
});
});
The required output of this code is:
processed: company // 1rst, because company model has no dependencies
processed: user // 2nd, because user requires company
processed: address // 3rd, because address requires company and user
I need to manage somehow the dependencies. The model.process
function should be triggered only when all the process
functions of the model's required models have already been resolved.
It's just a small example, I have a lot of models with multiple dependencies.
I need to trigger the download
functions synchronously, and trigger the process
function as soon as possible. I can not wait all the downloads to be resolved and call process
after.