在node.js中使用q的空承诺
我尝试使用节点js来实现状态机。 简化我使用q和promise的callback。 在某些情况下,调用特定状态的函数什么也不做。 但要在控制stream程中使用它,我需要一个解决的承诺。
所以我的状态是这样的。
// onstate.js module.exports = function(){ this.switchOn = function(){ var deferred = Q.defer(); deferred.resolve(); return deferred.promise; }; this.switchOff = function(){ var deferred = Q.defer(); object.switchOff() .then(function(result){ // changing to off-state deferred.resolve(); }, function(err){ deferred.reject(err); }); return deferred.promise; }; }
closuresfunction类似于Q实例中所述。 但是switchon函数呢? 我魔杖打电话给:
currentState.switchOn().then(foo(), bar());
我是否真的必须立即创build延期解决scheme,还是可以使用更简单的代码实现相同的行为?
您可以使用Q(value)
创build已解决的承诺。 在你的具体情况下,只需要Q()
。
文档: https : //github.com/kriskowal/q/wiki/API-Reference#qvalue
我需要一个解决的承诺。
Q
函数做到这一点,在ES6中它将是Promise.resolve(…)
。
我的代码看起来像这样
它大量使用延迟反模式 ! 你可以做
module.exports = function() { this.switchOn = function() { return Q(); // passing `undefined` }; this.switchOff = function() { return object.switchOff(); }; };
并仍然使用currentState.switchOn().then(foo, bar);
(注意我没有通过电话)。
- 如何Promisify这个function – nodejs
- 在Node.js模块函数之间传递数据库上下文
- 在sequelize getter方法中的asynchronous表查询
- Promise.resolve和new Promise(resolve)是可以互换的
- NodeJS与promise.catch和console.log的错误?
- 如何使用async.js中的Promise进行编码?
- 如何避免使用setTimeout来等待Promise解决?
- 如何在SailsJS / Waterline中使用Model.query()和promise?
- 在node.js中的for循环之后完成多个writeFile函数完成时的promise