Why won't my callback be attached to the end of this promise chain?

I'm losing my mind on this.

All I want to do is bind an array of functions (sync and async) and call back when everything is done.

A simple chaining function like this

function promise_chain(fns, start) {
    return fns.reduce(function(previous, next) {
        return previous.then(next);
    }, start);
}

really working on ordering things, but I can't get a callback at the end of it for my life. It returns the last in the promises chain, which should take a callback thenlike any other. But such a callback is triggered after the first element in the chain.

Here is the fiddle.

http://jsfiddle.net/v6YCL/

It also includes a variant of this chaining function, which confirms that the chain has a final 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;
}
+4
1

: then, , , , .

,

wait(2000)
  .then(function() { starter.resolve(); return chain; })
  .then(function() { message("end, state is: " + chain.state()); });

( )

wait(2000)
  .then(starter.resolve)
  .then(function() { message("end, state is: " + chain.state()); });

starter.resolve starter, , , , .then .

+3

Source: https://habr.com/ru/post/1529305/


All Articles