Decide whether to fulfill or deny a Promise at a later time in

When working on an Angular2/TypeScript project, a dialog is shown and the system returns a Promise object to the caller. This Promise will be resolved after the user closes the dialog.

The interface of the Promise class does not include methods like resolve() or reject(), so I need to save references to these methods in order to call them at a later time.

This approach seems less than ideal. Is there a more efficient way to handle this?

class Dialog {
    private resolve;
    private reject;

    show(): Promise<any> {
        var p = new Promise<any>((resolve, reject) => {
            // Save method references for later use
            this.resolve = resolve;
            this.reject = reject;
        });
        return p;
    }

    close() {
        this.resolve();
    }
}

Answer №1

I was in need of something similar to this, so I decided to create my own future class:

class Future<T> implements PromiseLike<T> {
    private promise: Promise<T>;
    private resolveFunction: (value?: T | PromiseLike<T>) => void;
    private rejectFunction: (reason?: any) => void;

    constructor(promise?: Promise<T>) {
        if (!(this instanceof Future)){
            return new Future(promise);
        }

        this.promise = promise || new Promise(this.promiseExecutor.bind(this));
    }

    public asPromise(): Promise<T> {
        return this.promise;
    }

    public then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Future<TResult>;
    public then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Future<TResult>;
    public then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => any): Future<TResult> {
        return new Future(this.promise.then(onfulfilled, onrejected));
    }

    public catch(onrejected?: (reason: any) => T | PromiseLike<T>): Future<T>;
    public catch(onrejected?: (reason: any) => void): Future<T>;
    public catch(onrejected?: (reason: any) => any): Future<T> {
        return new Future(this.promise.catch(onrejected));
    }

    public resolve(value?: T | PromiseLike<T>) {
        this.resolveFunction(value);
    }

    public reject(reason?: any) {
        this.rejectFunction(reason);
    }

    private promiseExecutor(resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) {
        this.resolveFunction = resolve;
        this.rejectFunction = reject;
    }
}

To use it, follow these steps:

let future = new Future<string>();

// Perform tasks and then:
future.resolve("A_VALUE");
// or reject the future:
future.reject("MESSAGE");

You can also store the future instance, return it, and then resolve/reject at a later time:

class MyClass {
    private future: Future<string[]>;

    constructor() {
        this.future = new Future<string[]>();
    }

    fetch(url: string): Promise<string[]> {
        ISSUE_HTTP_REQUEST(url)
            .then(this.future.resolve.bind(this.future))
            .catch(this.future.reject.bind(this.future));

        return this.future.asPromise();
    }
}

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

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

Encountering an Internal Server Error while setting up a Next.js Application

I recently decided to dive into Next.js and followed the tutorial on their official website, but unfortunately, I hit a roadblock. When I run npm run dev, I encounter the following error messages in my console and terminal: Failed to load resource: the ser ...

The tab title will be invisible if it is located within the second Angular component

Currently, I am utilizing the material css framework in combination with Angular (both latest versions). Everything works perfectly fine when I create tabs within one component. However, when I decide to make each tab a separate component, an issue arises ...

React - Incorporating Axios catch errors directly within form components

When a user registers, my backend checks if the email and/or username provided are already in use by another user. The response from Axios catch error is logged into the web console. I want to associate each email and username with their respective fields ...

Listening to a song on a webpage while filling out the online form

Seeking advice on integrating audio file selection in form: <form ....> <input type="file" name="file-main" id="file-main" class="inputfile inputfile-3" multiple/> <audio preload="none" src=""> // excluding submission buttons for brevi ...

Exploring the search feature within Redux and React-Native

The search functionality in redux is giving me some trouble. I have written the following code for it, but strangely enough, it's not working properly. Interestingly, the same code works perfectly when used without redux. searchItems: (name ) => ...

A guide on utilizing Socket.io to efficiently transfer data to a specific client within a designated chat room

Can someone please advise on the correct way to send data to a specific client in a specific room using socket io? The code snippet I have been trying is: I am using the following command: socket.to(socket.id).emit('change', {data}) However, i ...

What is the most reliable way to create an array ensuring that all potential values come from a specific dictionary?

I am seeking a method to define the testArray so that only keys from the example dictionary can be inserted into the array. enum example { key1 = 'A', key2 = 2, key3 = '3', }; const testArray: ?? = [example.key1, example.ke ...

Identify the Google Maps Marker currently displayed on the screen

Is there a way to generate a list of markers within the zoom range for Google Maps, similar to the functionality on this site I'm curious if I can achieve this using jQuery or if there is a built-in function for Google Maps v3? Thank you! ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...

How can I use AngularJS to save selected assets?

<div style="z-index: 1; position: absolute"ng-show="ctrl.company.selected"> <div style="" ng-repeat="Asset in ctrl.company.selected.Assets"> <div class="pd-5"style="width: 300px; background-color: white; border-bottom: gray solid ...

Retrieve JSON object from dropdown menu

I need to retrieve the object name from a dropdown menu when an item is selected. How can I access the object from the event itemSelect? Thank you for your attention. View Dropdown Menu XML code: <core:FragmentDefinition xmlns="sap.m" xmlns:c ...

What is the process for obtaining a push key in Firebase?

When a user submits data to the Firebase database, I need to handle the Key generated by that action in my own function. The challenge arises when a user fills out a form and sends data to our real-time DB. This data may include optional images, and I wan ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Activate the mandatory attribute once the checkbox associated with the field is selected

I am facing an issue with looping rows that contain checkboxes and dropdown lists. I want the dropdown list to be marked as required when its corresponding checkbox is selected in each row. MARK NAME QUANTITY ------------- ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

"I am eager to showcase the text upon pressing the Enter key, implementing an Immediately Invoked Function Expression

My input text box is supposed to store and display the output in an unordered list format when I hit enter. The function works fine without IIFE using onclick event, but it's not working with IIFE. Can anyone assist me with this issue? <html> ...

Selecting a single checkbox automatically selects all other checkboxes

Is there a way to automatically check all other checkboxes if one checkbox is checked? Here's the code snippet I have: <tr> <td class="small"><asp:CheckBox ID="chkReportModuleName" runat="server" name="report"></asp:CheckBox& ...

What is the best way to verify that a JSON key contains only distinct values within a JSON document using JavaScript?

I'm working with a JSON file structure that looks something like this: "fields": { "asset": { "values": [{ "asset": { "id": "Info_text", "type": "text", "value": "ABCD" } ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...