[英]Why won't my callback attach to the end of this promise chain?
I am losing my mind on this one. 我对这个失去了理智。
All I want to do is chain an array of functions (sync and async), and have a callback when they are all done. 我想做的就是链接一组函数(同步和异步),并在完成所有操作后进行回调。
A simple chaining function like this 像这样的简单链接功能
function promise_chain(fns, start) {
return fns.reduce(function(previous, next) {
return previous.then(next);
}, start);
}
does work to sequence things, but I cannot for the life of me to get a callback to fire at the end of it. 确实能够对事物进行排序,但是我不能为我的生命在其结束时获得回击。 It returns the last in a chain of promises, which should take a then
callback like any other. 它返回的最后一个链中的承诺,应当采用then
回调像任何其他。 But such a callback gets fired after the first item in the chain. 但是这样的回调在链中的第一个项目之后被触发。
Here is the fiddle. 这是小提琴。
http://jsfiddle.net/v6YCL/ http://jsfiddle.net/v6YCL/
It also includes a variant on that chaining function which confirms that the chain does have an end callback: 它还包含该链接函数的变体,它确认该链确实具有结束回调:
// This version prints the "resolved" message at the end as expected, but
// the message sequence is otherwise the same.
function wtf_promise_chain(fns, start) {
var _chain = $.Deferred();
$.when(fns.reduce(function(previous, next) {
return previous.then(next);
}, start).
then(function() {
message("chain resolved");
_chain.resolve();
}));
return _chain;
}
You are missing a subtle point: when you explicitly return a promise from the then
callbacks, the promise it returns in turn operates on that value. 您错过了一个微妙的观点:当您从then
回调中显式返回一个promise时,它返回的promise将依次对该值进行操作。
To get your desired behavior you would need to write 为了得到你想要的行为,你需要写
wait(2000)
.then(function() { starter.resolve(); return chain; })
.then(function() { message("end, state is: " + chain.state()); });
Your current version (copying it here for completeness) reads 您当前的版本(在此复制完整性)读取
wait(2000)
.then(starter.resolve)
.then(function() { message("end, state is: " + chain.state()); });
and since starter.resolve
returns starter
, which has obviously just been resolved, the second .then
causes the final message to be printed immediately. 并且由于starter.resolve
返回starter
,显然刚刚解析,第二个.then
导致最终消息立即打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.