Let's say I have a "JsonEditor" module (just for the example) which has 3 functions: get(), setProperty() and save().
Here is the code (the question follows):
var fs = require('fs')
, q = require('q');
var jsonEditorModule = (function() {
return {
get: function(jsonPath) {
// ...
},
save: function(jsonObject, jsonPath) {
var qJson = q.defer();
var jsonContent = JSON.stringify(jsonObject, null, 2);
fs.writeFile(jsonPath, jsonContent, function(err) {
if(err) {
qJson.reject(err);
}
else {
qJson.resolve();
}
});
return qJson.promise;
},
setProperty: function(prop, value, jsonPath) {
var self = this;
var qJson = q.defer();
this.get(jsonPath)
.then(
function(jsonObject) {
// Set the property
jsonObject[prop] = value;
// Save the file
self.save(jsonObject, jsonPath)
.then(
function() {
qJson.resolve();
},
function() {
qJson.reject();
},
);
}
);
return qJson.promise;
},
};
})();
module.exports = jsonEditorModule;
See the then() right after the save() in the setProperty() function ?
It looks stupid, right ?
Do I need to manually resolve() and reject() my promise ? Can't I just transfer the save() behavior to my setProperty() promise ?
Hope the question is clear enough (and not too stupid).
Thanks