以下代码返回:
output.isPending?: true
output.isRejected?: false
output.isFulfilled?: false
为什么呢?我期待output.isRejected
成为true
。
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.7/q.js"></script>
<script src="http://jasmine.github.io/2.3/lib/jasmine.js"></script>
</head>
<body>
</body>
<script>
var output, bar;
bar = {
doSomethingAsync: function() {
var d = Q.defer();
d.resolve('result');
return d.promise;
}
};
function Foo(bar) {
this._bar = bar;
this.go = function() {
var deferred = Q.defer();
this._bar.doSomethingAsync()
.then(onSuccess.bind(this, deferred));
return deferred.promise;
}
};
function onSuccess(deferred, result) {
deferred.reject();
}
output = new Foo(bar).go()
.finally(function() {
console.log('output.isPending?:', output.isPending());
console.log('output.isRejected?:', output.isRejected());
console.log('output.isFulfilled?:', output.isFulfilled());
});
</script>
</html>
答案 0 :(得分:5)
因为output
不是new Foo(bar).go()
。它会被分配.finally()
调用的结果,并且在finally
回调完成后仍无法解析。
这将按预期工作:
var output = new Foo(bar).go();
output.finally(function() {
console.log('output.isPending?:', output.isPending());
console.log('output.isRejected?:', output.isRejected());
console.log('output.isFulfilled?:', output.isFulfilled());
});
答案 1 :(得分:0)
我立即纠正了一个微不足道的延迟函数,即使是对于承诺无视的API也是不必要的。我可以确保始终调用resolve
或reject
,但是在承诺本身被立即返回之后。这是一个例子:
var somePromise = function(path) {
var deferred = q.defer();
asyncFunction.request(path, function(result) {
if (result.error === 0 && result.json !== null) {
deferred.resolve(result);
} else {
deferred.reject(result || {error: -1, message: "bad things happened"});
}
});
return deferred.promise;
};
exports.someCall = function(req,res) {
somePromise('path')
.then(function (result) {
... do action ...
}).catch(function (error) {
... handle error ...
});
};