javascript 为什么承诺仍然悬而未决?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30329485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is the promise still pending?
提问by Ben Aston
The following code returns:
以下代码返回:
output.isPending?: true
output.isRejected?: false
output.isFulfilled?: false
Why? I was expecting output.isRejected
to be true
.
为什么?我期待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>
采纳答案by Bergi
Because output
is not new Foo(bar).go()
. It is assigned the result of the .finally()
call, and will not be resolved untill the finally
callback is done.
因为output
不是new Foo(bar).go()
。它被分配了.finally()
调用的结果,并且在finally
回调完成之前不会被解析。
This will work as expected:
这将按预期工作:
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());
});
回答by Michael Shopsin
I stand corrected a trivial delay function is unnecessary even for API's that are oblivious to promises. I can make sure the resolve
or reject
is always called, but after the promise itself is returned without delay. Here is an example:
我更正了一个微不足道的延迟函数是不必要的,即使对于那些不注意承诺的 API。我可以确保resolve
orreject
总是被调用,但是在承诺本身被立即返回之后。下面是一个例子:
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 ...
});
};