A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise);

const finalPromise = new Promise<string>(resolve => {
    resultPromise.then(token => {
        if (Pending) {      
            resolve(token);
        } else if (!this.tokenIsValid(token)) {
            resultPromise = requestToken();
            resolve(resultPromise);
        } else {
            resolve(token);
        }
    });

I attempted to change it like this and encountered a TypeScript error:

//throwing error error noUnnecessaryCallbackWrapper: No need to wrap 'resolve' in another function. Just use it directly.

#second version
    const finalPromise = new Promise<string>(resolve => {
    resultPromise.then(token => {
        if (Pending) {      
            resolve(token);
        } else if (!this.tokenIsValid(token)) {
            requestToken().then(token => resolve(token)); 
        } else {
            resolve(token);
        }
    });

If I return resolve(resultPromise), what would be the type of finalPromise? My concern lies in another function receiving finalPromise where the input type is Promise<string>. How can I ensure that finalPromise returns a Promise of type string without causing any confusion? Your guidance is greatly appreciated.

Answer №1

In the comments, it was mentioned that you are utilizing the Promise constructor anti-pattern. To rectify this issue, it is recommended to directly chain your code to resultPromise.

Furthermore, you can streamline the handling of the requestToken call by returning it:

Typically, a value returned by a .then handler is immediately passed to the next handler. However, there is an exception.

If the returned value is a promise, then the execution will pause until the promise settles. Subsequently, the result of that promise is provided to the next .then handler.

(Quoted from this article)

This approach would lead to something similar to the following code snippet:

const finalPromise: Promise<string> = resultPromise.then(token => {
    if (Pending) {      
        return token;
    } else if (!this.tokenIsValid(token)) {
        return requestToken();
    } else {
        return token;
    }
);

// Later 
finalPromise.then(stringToken => console.log(stringToken));

The if-else statement could also be simplified, but due to uncertainty about the type of Pending, I did not make adjustments in this regard.


Just for your information: While it may not apply in your current scenario, if at any point you require multiple return types, AVOID USING any and opt for union type instead:

myAwesomeFunctionReturnStringOrNumber(): string | number {
   ...
};

myOtherFunctionTakeStringOrNumber(param: string | number) {
   ...
};

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

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

Creating a recursive setTimeout loop using Coffeescript

I am currently developing a live photo stream application. The idea is that users will be able to upload photos to a specific folder on my server via FTP, and the app should automatically update whenever a new photo is added, without needing to refresh the ...

Discovering the center of an element and implementing a left float

I'm looking for a way to dynamically position the element #ucp_arrow in the middle of a div using float: left. Here is an illustration: https://i.stack.imgur.com/nzvgb.png Currently, I have hard-coded it like this: JAVASCRIPT: $("#a_account").cli ...

Guidelines for transferring data when a button is held down or pressed

I am looking to continuously send values while a button is pressed. Currently, a value is only sent with each click. Below is the current code: my_custom_script.js $(document).ready(function() { $('#left').mousedown(function() { var left ...

Inserting a value into a Node/Express session

I am currently immersed in a project that involves Node, Express, and MongoDB. Mongoose is the tool I use to shape my schemas and interact with the database. In addition, I utilize the "express-sessions" module where a session value named "req.session.user ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

Transforming an array of strings into a Name/Value object using JavaScript

Recently, I encountered a Web Service that sends an array of strings to the client. My goal is to transform this array into an object where each string has a name for future reference. Let's start with: var result = ["test", "hello", "goodbye"]; An ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

Ways to implement the flow of change occurrences in the mat-select component

Seeking assistance with utilizing the optionSelectionChanges observable property within Angular Material's mat-select component. This property provides a combined stream of all child options' change events. I'm looking to retrieve the previ ...

What are the steps for making Ajax calls?

I have been working on a Wikipedia viewer for my freecodecamp project. However, I am facing issues with the AJAX request as it keeps failing every time without returning any results. var url, value; $(document).ready(function() { $("button").on("click ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

Struggling to align my image in the center while applying a hover effect using CSS

Hey there, I'm having an issue centering my image when I add instructions for it to tilt on mouseover. If I take out the 'tilt pic' div, the image centers just fine. Can anyone help me identify what I might be doing wrong? Thanks in advance! ...

What is the best way to search for an Enum based on its value?

One of my challenges involves an enum containing various API messages that I have already translated for display in the front-end: export enum API_MESSAGES { FAILED_TO_LOAD = 'Failed to load data', TOKEN_INVALID = 'Token seems to be inva ...

Forwarding to another page following an AJAX post request to a Django view

I've been struggling to get this basic piece of code to work properly, despite trying numerous resources. I can't seem to pinpoint where I'm going wrong. Essentially, I have a javascript function submitData() that is supposed to make an ajax ...

Separate the selected option in the TEXTAREA by commas to make it easier to

Can you assist me with integrating this example? I have the following elements: When adding a textarea, I require an option to be selected and separated by a comma. For instance: Here I will select an option: Subsequently, this chosen option must be ad ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Auto-fit HTML Webpage Resizer Simplified

Just finished my very first jQuery project, a simple full-width slider. I've been focusing on HTML & CSS and currently working with C#. The problem is that I don't want the page to be scrollable; I want it to autofit to the webpage. Imagine ope ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...