Incorporate a Promise within a function that creates and returns a new Promise

When working with Promises in javascript, it's important to be aware of anti-patterns that can arise. Let's consider a scenario where we have a request function that returns a Promise and we want to handle the response inside another function, executing specific code in the 'then' block, and then resolving or rejecting based on certain conditions:

export const login = (req: IRegisterAuthReq): Promise<IUserTokenResponse> => {
  return new Promise((resolve, reject) => {
    AuthApi.login(req)
      .then(response => {
        if (response.success) {
          store.dispatch(setUserLoggedIn(true));
          resolve(response.data as IUserTokenResponse);
        } else {
          reject();
        }
      })
      .catch(reject)
      .finally(() => {
        store.dispatch(setAppLoading(false));
      });
  });
};

In this code snippet, we're calling the AuthApi.login function, handling the response, and then resolving the value.

You can then use this code like so:

login(req)
  .then(authoredSuccessful)
  .catch(authoredUnsuccessful);

If you're unsure whether this approach is considered an anti-pattern or not, or if there might be a better way to achieve similar functionality, feel free to ask for advice on alternative methods.

Answer №1

I am seeking clarification on whether this approach is considered an anti-pattern or not, and if it is, what would be the best alternative method to achieve the same functionality.

Avoiding wrapping an existing promise with another manually created promise is recommended. Creating an additional promise can lead to unnecessary complexity and increase the likelihood of errors in error handling. You can refer to Promise anti-patterns for more information, specifically the "Construction Anti-Pattern". Additional promise-related anti-patterns can also be found here.

Instead, it is advisable to return the existing promise and utilize return values or exceptions within the .then() handler to manage the final resolved value of the promise chain.

export const login = (req: IRegisterAuthReq): Promise < IUserTokenResponse > => {
    return AuthApi.login(req).then(response => {
        if (response.success) {
            store.dispatch(setUserLoggedIn(true));
            return response.data;
        } else {
            // reject the promise chain
            throw new Error("login not successful");
        }
    }).finally(() => {
        store.dispatch(setAppLoading(false));
    });
};

Answer №2

In my opinion, it's more visually appealing to chain promise calls like this:

export const login = (req: IRegisterAuthReq): Promise<IUserTokenResponse> => {
  return AuthApi.login(req)
      .then(response => {
        if (response.success) {
          store.dispatch(setUserLoggedIn(true));
          return response.data as IUserTokenResponse;
        }
        throw new Error("Auth error")
      })
      .finally(() => store.dispatch(setAppLoading(false)));
};

Alternatively, you can use async/await for a cleaner code structure:

export const login = async (req: IRegisterAuthReq): Promise<IUserTokenResponse> => {
  const response = await AuthApi.login(req);
  
  try {
    if (response.success) {
      store.dispatch(setUserLoggedIn(true));
      return response.data as IUserTokenResponse;
    }
  
    throw new Error("Auth error");
  } finally {
    store.dispatch(setAppLoading(false));
  }
};

Answer №3

If you want to achieve this, you can follow the example below:

login()
.then( () => {
  handleSuccess()
})
.then( () => {
  doAnyOtherPromise()
})
.catch( error => {
  // The error here may come from any of the previous promises
  console.log(error)
});

To learn more about using promises, check out this resource

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

Obtain the specific generic type that is employed to broaden the scope of a

I am working on a class that involves generics: abstract class Base<P extends SomeType = SomeType> { // ... } In addition, there is a subclass that inherits from it: class A extends Base<SomeTypeA> { // ... } I'm trying to figure out ...

Include a checkbox within a cell of a table while utilizing ngFor to iterate through a two-dimensional array

I am working with a two-dimensional array. var arr = [ { ID: 1, Name: "foo", Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5939a9ab5939a9adb969a98">[email protected]</a>", isChecked: "true" ...

Refreshing an Angular directive when a parameter is modified

My angular directive is set up like this: <conversation style="height:300px" type="convo" type-id="{{some_prop}}"></conversation> I want the directive to automatically refresh when $scope.some_prop changes, so that it displays different conte ...

Building collapsible table cell components using ReactJS and Bootstrap 4

For each table row, I need to implement a feature that allows users to click on it and view specific information related to that row. After doing some research, I came across this thread: Twitter Bootstrap Use collapse.js on table cells [Almost Done] I ma ...

Javascript 'break' statement is always executed

It seems like I'm overlooking a very basic concept here. Why isn't my code reaching the else statement? The issue might be related to the break statement. It's likely something simple that I am missing. Code Snippet: <button onclick="yo ...

The server failed to respond to the Angular HTTP request

To store data in my database, I have created a function in my component.ts file that invokes a service: ajoutText(newtext: String) { this.dataService.sendtext(newtext); } On the HTML side, it looks like this: <form class="form"> <mat-form-f ...

What could be causing my reduce() method to function properly when I declare the array in TypeScript, but not when I utilize a model file?

I have defined an object in my TypeScript file and utilized the reduce() method without any issues. Here is the code snippet: sampleList = { totalRecordsTest: {}, sampleList: [ { parent: 'Sample Text 2', children: ...

What is the best way to include JavaScript in a web view within an Ionic Android application?

I'm in the process of incorporating a header bar into the web view for my app. Utilizing the cordova inAppBrowser plugin to achieve this, I tested using the following code: var win = window.open( URL, "_blank", 'location=yes' ); win.addEven ...

What impact does using javascript to toggle the readonly property of a textarea have on alert prompts?

I have implemented a feature on my webpage where textareas initially load as readonly, and I would like users to be able to toggle this property by double-clicking on them. However, I have encountered an issue with the listener events in my JavaScript fil ...

The functionality to redirect in Wordpress Contact Form 7 based on the value of a radio button selection does

For the past 5 hours, I have been diving deep into Contact Form 7 redirects that are based on values. Despite my efforts, I am unable to figure out why my code isn't functioning properly. Is there anyone who can spot the issue? Contact Form Radio But ...

Calculating the average value of an attribute in an array using Mongodb (Mongoose)

Seeking assistance with a query to find sellers near users based on location input and sorting them by average rating. Is this achievable? Snippet of the model including an array of reviews: const sellerSchema = new mongoose.Schema({ _id: Mongo ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...

Ways to determine if a particular string is present in a web browser

Can someone please help me figure out how to verify the presence of a specific text string in a web browser? Specifically, I need to confirm if the phrase "Hello World" is displayed on the browser. Any guidance on this matter would be highly appreciated. ...

Angular threw an error saying: "Template parse errors: is not a recognized element"

I am attempting to utilize babel standalone within a react application to transpile Angular TypeScript. The transpiling process seems to be successful, however, I encounter an error when trying to import a component and use its selector within the template ...

A guide on utilizing a controller again in AngularJS while adjusting variables according to different routes

My task involves loading a web service and I found the angular method of displaying, sorting, and filtering tables to be very effective. Now, I am looking to enhance this functionality. Depending on the selected link, I want to show different data from the ...

Launching an app using Electron JS incorporating an Express backend and a standalone HTML frontend

I have a unique situation where my application consists of separate ExpressJS backend and HTML front-end modules. The ExpressJS backend is located at root/scripts/server.js Meanwhile, the HTML front-end is situated in root/index.html. The front-end utili ...

Trigger the Input event on Android with Nuxt

A unique issue has arisen with an input field that filters a list whenever a key is pressed, displaying the filtered results in the browser. While the functionality works perfectly on desktop, it behaves strangely on Android mobiles. The list only shows up ...

Challenges encountered when submitting forms on a standalone HTML webpage

In my HTML page, I have multiple forms that operate independently of each other and use AJAX to avoid a complete page reload. https://i.sstatic.net/WiGbv.png For example, one form is used for search functionality. After performing the search using AJAX, ...

Retrieving dropdown options with the help of selenium and node.js

I'm looking to gather all the options from a dropdown menu and loop through them to submit a form. I need the list of values from the dropdown. The following Java code meets my requirements perfectly, but I am in need of the same functionality in Jav ...

Utilizing TypeScript with dc.js for enhanced data visualization capabilities

I've encountered an issue with types while working with dc.js version 4.2.7. To address this, I went ahead and installed what I believe to be the standard types module for dc.js using the following command: Command I used for Installation npm i @type ...