The functionality of arguments in the whenAllDone promise/deferred javascript helper seems to fail when attempting to encapsulate existing code within a Deferred

My goal is to implement the solution provided in TypeScript from Stack Overflow:

UPDATE 2 - The issue with the original answer is that it does not support a single deferred. I have made modifications to reproduce the error in his fiddle. http://jsfiddle.net/3h6gwe1x/

UPDATE 1 - It turns out the problem lies in my usage, so I am updating the question to clarify this further.

Initially, I had a method called submitCalculation which made an AJAX call and I passed a callback handler to be executed upon completion. Everything worked fine until the requirement arose to potentially run multiple submitCalculation calls and wait for all of them to finish. Thus, I tried wrapping the original call inside a Deferred object as shown below.

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 }[] ) { ... } );

During execution of the whenAllDone method when the following block of code is reached, the parameter arguments is not structured correctly.

$.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 response's fiddle, the structure of arguments was in the form of

[ true|false, currentDeferredArguments ][]
. Each element in the array represented the array of parameters resulting from
currentDeferred.resolve(true|false, arguments);
.

https://i.sstatic.net/2i2UE.png

However, in my case, the array is flattened and takes the form of

[true|false, currentDeferredArguments]
. So when looping through the arguments using
$.each(arguments, function (i, args) {
, my args do not conform to an 'array'. The initial args simply represents a boolean value from the currentDeferred.resolve call, thereby affecting the logic within the loop.

https://i.sstatic.net/1hYdY.png

If I modify my code to test it similarly to the working example provided:

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(

How can I properly wrap my original submitCalculation call to ensure the correct behavior of returning a deferred object for whenAllDone functionality?

Answer №1

The issue stemmed from a section within jquery's when function.

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

A specific line in the code read:

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

This altered the structure of the arguments, requiring me to adjust it back to match the standard format my code relies on (similar to 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);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scale up each image with the use of Java script

I have a main container with three different sub-containers, each containing an image and text. I want to achieve the effect of zooming in on the image of the specific sub-container when hovering over it. Currently, when I hover over any sub-container, all ...

Using jQuery to swap an image with a div element and then using the image as the

I have a collection of images in a div, like so: <div class="image-container"> <img width="174" height="174" src="http://mysite.com/images/portfolio/p1.jpg" class="image-style" typeof="foaf:Image"> <img width="174" height="174" src= ...

The sign-up button mysteriously vanishes after the page is refreshed

I am encountering an issue with the sign up button during the user registration process. There is a checkbox for Terms & Conditions, and the button should only become enabled after checking this box. Everything seems to be functioning correctly, but when I ...

Hover over the text to disable the input element and display it as a textbox

Currently, I have a situation where I have two text boxes - when text is entered into textbox1, textbox2 becomes disabled as expected. However, my second requirement is that upon disabling textbox2, hovering over it should display the message "You can ente ...

I need help creating a functional Component in react and utilizing destructive assignment. I attempted to write some code but it doesn't seem to be functioning properly

Can someone help me convert this into destructive assignment? I keep getting the error message Binding element 'onClickBackDrop' implicitly has an 'any' type.ts(7031) I'm struggling to figure out where I went wrong import React ...

Choose an XPath formula that will target every single element, text node, and comment node in the original sequence

How can we write an XPath expression that selects all elements, text nodes, and comment nodes in the order they appear in the document? The code below selects all elements but not text nodes and comment nodes: let result = document.evaluate('//*&apo ...

Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript: [{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

Determining the element type that was clicked using Angular

Is there a way in Angular to determine the type of element that was clicked? I have successfully implemented this functionality using jQuery, but I'm unsure how to achieve the same outcome in an Angular project. // Click action $(".contactlist").on(" ...

How to delete items containing NULL values from a JSON array using JQuery/JavaScript

While browsing through StackOverflow, I came across some questions related to this topic, but none of the solutions I found seemed to work for me. It appears to be a common issue, and I suspect that I might not be constructing the JSON object correctly. M ...

drag items on your smartphone with ease

Hello everyone, I am looking to make items draggable on a smartphone as well. Here is my HTML code: <input class="inputText mb-2 border border-primary rounded" v-model="newTodo" @keypress.13='addTodo' placeholder="W ...

Guide on embedding PHP code into a HTML div element using JQuery

I am having trouble loading PHP code into a div tag to display the results. The code I have listed below does not seem to work for me. If anyone can offer assistance in resolving this issue, I would greatly appreciate it. Here is the code snippet: <h ...

Components can be iterated over without the use of arrays

In my component, I have a render that generates multiple components and I need some of them to be repeated. The issue I am facing is that when I create an HTML render, the variable is not being processed and it just displays as text. Although the actual c ...

update and rejuvenate session information using Node.js and express-session

Currently, I am working with Node.js in conjunction with express-session. Within my codebase, there is session data containing user information. req.session.user Upon updating the user's information, I update the session with the new data and then r ...

What is the best way to reposition the caret within an <input type="number"> element?

How can I make the caret move when an input is clicked? The code I found works with text, but not with number. Also, is there a way to pass the length without specifying a value (e.g. 55) in the parameters? HTML <input type="number" name="cost" value= ...

Ways to determine in each() whether the current div contains a specific class or not

My task is to verify if the div contains the class 'completed', and then insert the text "Hello". However, my current code is displaying "Hello" even when the div does not have the class 'completed'. jssfiddle ...

What is the best method for distributing an Angular service from a library created using ng generate library?

I'm currently facing a challenge in sharing a service from the npm package that I created using ng g library with my Angular hosting application. While I have experience in linking components and directives, I'm a bit lost when it comes to servic ...

Issues with jQuery AJAX, occasionally experiencing repeated requests

Currently, I am in the final stages of revamping our JavaScript system by transitioning from Prototype to jQuery. We have numerous AJAX requests that are triggered when specific events occur on certain elements. One instance of this is when a new event is ...

The lack of definition for the props value poses an issue in React.js Hooks

I'm currently developing a notepad web application that utilizes React Hooks for managing state variables. In order to fetch data from an API, I am using the axios library. The retrieved data consists of objects with fields such as _id, title, status, ...

Changing the Flash message to an Alert message in Symfony2: A step-by-step guide

I've encountered a problem where the success message from an action method in Symfony2 Controller appears as a flash message, but I need to display it as an alert or dialogue message according to requirements. I have attempted various solutions witho ...