1

I'm trying to implement the following in TypeScript: https://stackoverflow.com/a/15094263/166231

UPDATE 2 - The problem with original answer is that it doesn't support a single deferred. I modified his fiddle to reproduce the error. http://jsfiddle.net/3h6gwe1x/

UPDATE 1 - Issue is in my usage, so modifying question to indicate that more clearly.

Originally, I had a submitCalculation method that called .ajax, so I passed a callback handler in to be called when it was done. This all worked, but I have to prepare for having to run 1..N submitCalculation calls and wait until all were done. So this was my attempt to simply wrap the original call inside a Deferred.

const p = function() {
    const d = $.Deferred();

    try {
        that.rble.submitCalculation( 
            currentOptions,
            ( errorMessage, result ) => { 
                if ( errorMessage != undefined ) {
                    d.reject( { "Options": currentOptions, "ErrorMessage": errorMessage } );
                }
                else {
                    d.resolve( { "Options": currentOptions, "Result": result } );
                }
            } 
        );
    } catch (error) {
        d.reject( { "Options": currentOptions, "ErrorMessage": "ReSubmit.Pipeline exception: " + error } );
    }

    return d;
}

$.whenAllDone( p() ).then( 
   function( ... successes: { Options: KatAppOptions, Result: RBLResult }[] ) { ... },
   function( ... failures: { Options: KatAppOptions, ErrorMessage: string }[] ) { ... } );

When the whenAllDone method is running and hits the following code, the arguments parameter is not right.

$.when.apply($, deferreds).then(function() {
    var failures = [];
    var successes = [];

    $.each(arguments, function(i, args) {
        // If we resolved with `true` as the first parameter
        // we have a failure, a success otherwise
        var target = args[0] ? failures : successes;
        var data = args[1];
        // Push either all arguments or the only one
        target.push(data.length === 1 ? data[0] : args);
    });

    if(failures.length) {
        return result.reject.apply(result, failures);
    }

    return result.resolve.apply(result, successes);
});

In the original answer's fiddle, the arguments was in the form of [ true|false, currentDeferredArguments ][]. Each element in the array, was the array of parameters resulting from currentDeferred.resolve(true|false, arguments);.

enter image description here

However, mine is a flattened array in the form of [ true|false, currentDeferredArguments ]. So when I loop the arguments in $.each(arguments, function (i, args) {, my args are never an 'array'. The first args is simply a boolean from the currentDeferred.resolve call, which then obviously screws up the logic in that loop.

enter image description here

If I change my code to simply test code the way he did (as in the following) it works as expected.

var dfd1 = $.Deferred();
var dfd2 = $.Deferred();

setTimeout(function () {
    console.log('Resolve dfd2');
    dfd2.reject( { "Options": currentOptions, "ErrorMessage": "Test 2" } );
}, 200);

setTimeout(function () {
    console.log('works dfd1');
    dfd1.reject( { "Options": currentOptions, "ErrorMessage": "Test 1" } );
}, 100);

$.whenAllDone( dfd1, dfd2 ).then(

So how can I correctly wrap my original call to submitCalculation to correctly return a deferred object so whenAllDone works?

Terry
  • 2,148
  • 2
  • 32
  • 53
  • This line differs: `var target = !args[0] ? failures : successes;` Your code has `!args[0]` the original has just `args[0]` – Heretic Monkey Feb 15 '21 at 17:30
  • Yeah, I just flipped the true|false logic. A value of `true` meant 'success' to me more than failure. Good eye, but that isn't causing the issue. – Terry Feb 15 '21 at 17:37
  • This is all very complicated and using deferred, which really is old-style. Your question doesn't clearly define what you want to achieve (best with a very very concrete example of input and output). But I wonder if you cannot do all of this with the native [`Promise.allSettled`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled). – trincot Feb 15 '21 at 17:54
  • @trincot How that never showed up when I was googling 'wait for all promises' or other variations is beyond me. And it does look promising :) So I will try that, but see updated/changed question as my problem was in how I was creating a deferred. Maybe you'll spot something there to help. – Terry Feb 15 '21 at 17:58
  • I am not in deferreds anymore: that is a thing of the past. – trincot Feb 15 '21 at 18:13
  • @trincot `allSettled` is not supported by IE?! Nuts! I still need to support that thing. If deferreds are thing of past, what is current? – Terry Feb 15 '21 at 18:32
  • Promises are current. And I would stop using `fail`, `done`, `success`, and the other jQuery methods like that. The standard is `then` and `catch`. You don't need anything else. – trincot Feb 15 '21 at 18:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228759/discussion-between-terry-and-trincot). – Terry Feb 15 '21 at 19:22
  • I would have a go at this question, but there are several things unclear. The question should be self-contained (I should not have to follow a link to find info that is essential). It has images of code (please don't). It should just include a Stack Snippet fiddle in the question demonstrating the issue. And add to it what the expected output would be for that snippet. I have read your question a few times now, and half way I am getting lost each time. For instance, there is `$.whenAllDone( p() )`, where `p()` returns one deferred, yet it looks like you expect more... – trincot Feb 15 '21 at 19:50

1 Answers1

0

The problem was inside jquery's when method.

jquery.when: function( subordinate /* , ..., subordinateN */ ) { ...

It has a line like:

// If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),

And this changes the shape of the arguments, so I had to put it back to the common shape my code expects (i.e. the same shape when multiple deferreds are passed to whenAllDone)

const deferredArgs = jqueryWhenUsesSubordinate
    ? [[ arguments[ 0 ], arguments[ 1 ] ]]
    : arguments

$.each(deferredArgs, function (i, resolvedArgs) {
    var target = !resolvedArgs[0] ? failures : successes;
    var data = resolvedArgs[1];
    target.push(data.length === 1 ? data[0] : data);
});

Terry
  • 2,148
  • 2
  • 32
  • 53