The challenge of handling native promise resolution when it occurs outside of a function

Currently, I am in the process of refactoring jQuery promises using native promises for the following code snippets.

public functionA(){
    const dArray = Array<JQueryDeferred<{a:string}>>=[];
    //other lines of logic
    functionB(dArray, /*other parameters*/);

}

private functionB(dArray : Array<JQueryDeferred<{a:string}>>[], /*other arguments*/){
    //other lines of logic
    for(var i=0;i<10;i++){
        dArray.push($.Deferred());
        var ele = dArray.length-1;

        functionC(dArray[ele], /*other parameters*/)
            .done((result: { a:string}) => {
                // logic
            })
            .always() => {
                // some additional logic
        });
    }
}

private functionC(d: JQueryDeferred<{a:string}>):JQueryDeferred<{a:string}>{
        if(){//some condition

           // some other logic 
           d.resolve({ a: "completed" });

        }
    return d;
}

The current methods involve passing deferred objects to multiple functions and an array of deferred objects. I am looking for assistance in finding a better way to rewrite the code using native promises as shown below;

public functionA(){
    const pArray = Array<Promise<{a:string}>>=[];
    //other lines of logic
    functionB(pArray, /*other parameters*/);

}

private functionB(pArray : Array<Promise<{a:string}>>[], /*other arguments*/){
    //other lines of logic
    for(var i=0;i<10;i++){
        pArray.push((new Promise<{ a:string; }>(resolve => resolvePromise = resolve)););
        var ele = pArray.length-1;

        functionC(pArray[ele], /*other parameters*/)
            .then((result: { a:string }) => {
                // logic
            })
            .finally() => {
                // some additional logic
        });
    }
}

private functionC(p: Promise<{a:string}>):Promise<{a:string}>{
        if(){//some condition
           // some other logic 
           // i am stuck here..
           p.resolve({ a: "completed"}) //no such resolve method to call
           // tried with Promise.resolve({ a: "completed"}), 
           // but my question - will it resolve same way as the index based 
           // resolve like the jQuery deferred version?

        }
    return p;
}

Thank you for any help provided.

Answer №1

Instead of being callbacks passed into a function, promises are result values that are returned from a function. When constructed inside a function, they can only be resolved by the logic within that function. Unlike Deferred objects, promises cannot be resolved by just anyone who has access to them.

To implement this correctly in code, you should follow this structure:

public functionA() {
    // Include other lines of logic
    const pArray = functionB(/* other arguments */);
}

private functionB(/* other parameters */): Array<Promise<{a:string}>> {
    // Include other lines of logic
    const promises: Array<Promise<{a:string}>> = [];
    for (var i=0; i<10; i++) {
        promises.push(
            functionC(/* … */).then((result: { a:string }) => {
                // Add your own logic here
            }).finally() => {
                // Further additional logic 
            })
        );
    }
    return promises;
//  ^^^^^^^^^^^^^^^
}

private functionC(): Promise<{a:string}> {
    return new Promise<{ a:string; }>((resolve, reject) => {
//  ^^^^^^^^^^^^^^^^^^
        if (/* some condition */) {
           // Implement other logic
           resolve({ a: "completed"});
        } else {
           reject(new Error());
        }
    });
}

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

Bootstrap 4 Carousel featuring Shadowed Circles

I am attempting to incorporate two features into a Bootstrap 4 carousel: 1- Add shadow to the text on top of the image in the carousel-caption 2- Display indicators in circular format with numbers inside them I would like the final result to resemble th ...

Navigating the intricacies of platform-specific settings in JavaScript

Currently, I am in the process of transferring an application from one PHP-based CMS to another (such as Wordpress, Joomla, etc.). I have established classes that enable my code to function seamlessly on each platform without any alterations (so far so goo ...

Setting up eslint for your new react project---Would you like any further

I am currently working on a TypeScript-based React application. To start off, I used the following command to create my React app with TypeScript template: npx create-react-app test-app --template typescript It's worth noting that eslint comes pre-co ...

Sorting can be done in a table that is scrollable

Can someone recommend a sortable table with scrolling and a fixed header? I'm looking for a solution that can be implemented using either jQuery or plain JavaScript. Your input is greatly appreciated. Thank you! ...

Guide on how to turn off a checkbox "toggle switch" using JavaScript

Being relatively new to CSS and HTML, I recently experimented with creating a checkbox toggle switch using this resource. I now have a specific requirement to disable this toggle switch upon clicking a different button labeled 'Reset', making it ...

Issue with connecting React Router v4 to Redux - dispatch function not being properly passed

Recently, I've been working on migrating my app to React Router v4 and encountered some challenges due to the significant changes in the API. Here's where I currently stand: Setting Up the Router const createStoreWithMiddleware = applyMiddlewar ...

Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this: { shape:[ 'SphereGeometry', [7, 16, 16] ] } My goal is to load a model using the following code: new THREE[shape[0]].apply( this, shape[1] ) However, it seems that using "new" and " ...

Trigger a re-render of specific components upon clicking a button in React

Within my server file, there is a function that retrieves a specific set of data based on an ID. app.get('/musicbyid', function(req, res){ var query = req.query.term.toLowerCase(); music.find({ _id: query }, function(err, allMusic){ ...

The issue of Basic Bootstrap 5 Modal triggering twice is causing a frustrating experience

My modal is almost working perfectly - it changes content based on the clicked image, but it is triggering twice in the backend and I can't figure out why! I followed Bootstrap's documentation for this, so I'm unsure where the issue lies. Al ...

Creating a Pie Graph using Angular 5

Looking to create a pie chart in Angular 5 using hard coded data that is not from an API. The chart should be based on expiration and lot status. Here's the code snippet: component.html <ng-container matColumnDef="expiration"> <mat-header ...

Transform a string with delimiter into a JSON object containing key-value pairs extracted from the string

Looking to transform a string into an object in typescript for NodeJS API var string = "1234|Tom|NYC|Student|Active" The goal is to map the string to: { "Id": 1234, "Name": "Tom", "City": "NYC ...

Can we implement attribute selectors in Material-UI while utilizing makeStyles?

Is it possible to extract all the div elements with specific Mui class names such as access-MuiPickersCalendarHeader-switchHeader, access-MuiPickersDay-day? My components are styled using StylesProvider which adds "access" as a prefix to the original Mater ...

Printing in HTML is limited to only one page

While printing an HTML table that can vary in length, I often encounter the issue of it printing multiple pages. Is there a way to limit the printing to just one page through coding? Yes, you can achieve this by using the option in the browser print dialog ...

Encapsulating constructor variables in TypeScript classes through private access modifiers and using public getters

Coming from a background in C#, I am used to designing most of my classes to be immutable. I am curious about whether it is considered good practice in TypeScript to use private constructor variables and public getters for accessing data within classes. T ...

Retrieving file icons from a directory using Node.js fs

I am interested in creating a file system explorer application that displays files with icons. I am using node-webkit and the files can be executables, directories, or regular files. In the file list, I want to show the file's icon and name. Is it po ...

Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in: ...

What is the most effective method for flipping a THREE.Sprite in r84?

After updating my game engine from r69 to r84, I encountered a few issues. One of them is related to flipping sprites. In the past, I could easily flip sprites using the following code: sprite.scale.x = -1; Unfortunately, this method no longer works in ...

The PageMethods not invoking the code-behind method as expected

I've been attempting to call a simple code behind C# method using PageMethods (AJAX). I have set EnablePageMethods = true and made my code behind method as WebMethod public static. I even tried ScriptMethod with WebMethod but nothing seems to be worki ...

Is there a way to determine if a server firewall such as mod_security is preventing jQuery Ajax connections?

If I encounter a scenario like this: https://i.sstatic.net/3JqI9.png How can I detect this situation using jQuery AJAX? The connection seems to hang without any HTTP Status Code, and there are no AJAX errors detected even though the file exists. I attem ...

Is it possible for Angular.js to access a server session attribute?

I am in the process of creating an authentication system with angular.js My goal is to implement a session timeout after a period of inactivity and expire the current session if a user logs in from another device. In both scenarios - 1) idle timeout and ...