Node.js Q承诺,为什么使用defer()的时候可以使用this()?
我想做一些事情:
somePromiseFunc(value1) .then(function(value2, callback) { // insert the next then() into this function: funcWithCallback(callback); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done();
它没有工作。 我无法得到它的工作。 我被build议使用defer()
来达到这个目的。
他们自己的文档说,我们应该使用延迟callback式函数。 虽然这是令人困惑的,因为他们着名的金字塔榜样都是关于callback的,但是这个例子太抽象了。
因此,我看到很多使用defer
的人,那就是我所做的:
somePromiseFunc(value1) .then(function(value2) { var promise = q.defer(); funcWithCallback(function(err, dronesYouAreLookingFor){ if (!err) promise.resolve(dronesYouAreLookingFor); else promise.reject(new Error(err)); }); return promise.promise; }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done();
直到我通过检查源代码发现这也起作用:
somePromiseFunc(value1) .then(function(value2) { return function() { funcWithCallback(arguments[1]); }; }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done();
为什么我不应该使用这个更简单的无证书版本?
未logging,因为虽然这看起来像金字塔是什么变平 , return function(){withCB(arguments[1])}
工作,而return function(err, cb){withCB(cb)}
不。
这不是使用承诺库的合法方式。 正如Q旨在遵守的承诺规范中所详述的那样,您从一个不是承诺的callback中返回的任何东西都应直接通过。
当使用promise时,基本上基于callback的代码应该被视为legacy
。
你有两个基本的select。 如果你使用funcWithCallback很多次,你可以这样做:
var promisedFunc = Q.nfbind(funcWithCallback); somePromiseFunc(value1) .then(function(value2) { return promisedFunc(); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done();
或者如果你需要传递参数:
var promisedFunc = Q.nfbind(funcWithCallback); somePromiseFunc(value1) .then(function(value2) { return promisedFunc(value1, value2); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done();
如果你只能使用它,一旦你可以做
somePromiseFunc(value1) .then(function(value2) { return Q.nfcall(funcWithCallback); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done();
或者如果你需要传递参数:
somePromiseFunc(value1) .then(function(value2) { return Q.nfcall(funcWithCallback, value1, value2); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done();