假设我有一个“ jsoneditor”模块(仅用于示例),它具有3个功能:get(),setproperty()和save().
这是代码(问题如下):
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;
看到setproperty()函数中save()之后的then()吗?
看起来很蠢,对吧?
我是否需要手动解决我的诺言和拒绝我的诺言?
我不能只是将save()行为转移到我的setproperty()Promise吗?
希望这个问题足够清楚(不要太愚蠢).
谢谢
解决方法:
您想要实现的目标在此处进行了描述:chaining,基本上,如果处理程序返回了一个Promise(我们称它为innerPromiseFromHandler),那么当innerPromiseFromHandler获得一个分辨率值时,将执行在上一个诺言中定义的.then的处理程序:
var jsoneditorModule = (function() {
return {
get: function(jsonPath) {
return Q.delay(1000).then(function () {
document.write('get...<br/>');
return 'get';
});
},
save: function(result) {
return Q.delay(1000).then(function () {
document.write('save...<br/>');
return result + ' save';
});
},
setProperty: function(prop, value, jsonPath) {
return this.get(jsonPath)
.then(function(result) {
return jsoneditorModule.save(result);
});
}
};
})();
jsoneditorModule
.setproperty()
.then(function (result) {
document.write(result + ' finish');
})
<script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.2/q.js"></script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。