execute a series of asynchronous functions one after another

async function cancelUserSubscriptionHandler() {
  const unsubscribe = await fetch("/api/stripe-sessions/cancel-subscription", {
    method: "PATCH",
    body: JSON.stringify(),
    headers: {
      "Content-Type": "application/json",
    },
  });
  const data = await unsubscribe.json();
  if (!unsubscribe.ok) {
    Toast.fire({
      icon: "error",
      title: `${data.message}`,
    });
  } else {
    Toast.fire({
      icon: "success",
      title: `${data.message}`,
    });
  }
}

async function deleteUserAccountHandler() {
  const deleteUser = await fetch("/api/user/delete-account", {
    method: "DELETE",
    body: JSON.stringify(),
    headers: {
      "Content-Type": "application/json",
    },
  });
  const data = await deleteUser.json();
  if (!deleteUser.ok) {
    Toast.fire({
      icon: "error",
      title: `${data.message}`,
    });
  } else {
    Toast.fire({
      icon: "success",
      title: `${data.message}`,
    });
  }
}

const deleteAccountProcess = async () => {
    try {
        await cancelUserSubscriptionHandler();
        await deleteUserAccountHandler();
    } catch (err) {
        console.error('ERROR@@@@@!!!',err);
    }
}

const SettingsPage = () => {
  return <DeleteAccount onDeleteAccount={deleteAccountProcess} />;
};

As demonstrated above, the process involves canceling a user subscription before deleting the account.

A known issue is that only one handler is executed and not both. Is there an alternative approach?

I have attempted:

.then(() => deleteUserAccountHandler())

and

.then(deleteUserAccountHandler)

However, neither option calls the /api/user/delete-account endpoint,

resulting in only the unsubscription being performed.

Answer №1

This is incorrect:

const deleteAccount = () => unsubscribeUserHandler()
    .then(deleteUserHandler())
    .catch(console.error);

Instead of passing deleteUserhandler to then(), you are immediately calling it and passing the result to then().

To correct this, remove the parentheses:

const deleteAccount = () => unsubscribeUserHandler()
    .then(deleteUserHandler)
    .catch(console.error);

Alternatively, use an arrow function:

const deleteAccount = () => unsubscribeUserHandler()
    .then(() => deleteUserHandler())
    .catch(console.error);

Or even better:

const deleteAccount = async () => {
  try {
    await unsubscribeUserHandler();
    await deleteUserHandler();
  } catch (err) {
    console.error(err);
  }
}

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

Using two different Readable streams to pipe to the same Writable stream multiple times

In my current project, I am facing the challenge of concatenating a string and a Readable stream. The Readable stream is linked to a file that may contain data in multiple chunks, making it quite large. My objective is to combine these two entities into on ...

Troubleshooting a glitch with passing a variable to a PHP script using AJAX

Explanation of the page functionality: When the quiz php page loads, a user can create a score using a function in quiz.js. This score is then stored in a variable score within quiz.js Once the score is generated, the user must click a button to move on ...

Navigating between pages using React and Material UI

My concept involves a <LandingPage> with a <Top> element that can be modified by user interaction. The <Top> component contains a pageState, which can be changed by clicking buttons on the First and Second pages. Is this considered good ...

Is there a way to execute .jsx Photoshop scripts on images using Java?

Currently, I am in the process of developing a Java program to apply edits to a sequence of images. However, I am searching for a simple and adaptable method to conduct these edits by utilizing Image Editors Scripts (such as Photoshop Scripts, Gimp Scripts ...

Using JQuery to create an animated slideToggle effect for a multicolumn list

I have a large list where each li element has a width of 33%, resulting in 3 columns: computers monitors hi-fi sex-toys pancakes scissors Each column contains a hidden UL, which is revealed through slideToggle on click. JQuery $('.subCate ...

Jquery refuses to load

Hey everyone! I'm currently working on an HTML file for my Angular 2 course. After setting up the dependencies and downloading them with npm, I encountered an error when trying to run the app... The error message I received was: file:///Users/Rocky/A ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

Trouble with Fetching Data by ID in MongoDB 2.0.0 Driver

In my NodeJS/Express web service project, I am using the MongoDB 2.0.0 driver to interact with the database. UPDATE: Following previous feedback, I have made changes to my code, including removing the db.close() call. Everything works smoothly when I per ...

Having trouble getting data to send to node.js server using $.ajax post

Trying to convert a table date into an array and send it to the server side using Ajax post for the first time. Despite following all the suggestions in previous posts, I am still struggling. Utilizing body-parser to extract data on the server side. Any he ...

When invoking the jQuery ".load('pageName')" method, HTML pages are not loaded from the application cache

I have been working on incorporating the html5 offline caching functionality into our html pages, and everything seems to be running smoothly with jQuery version 1.4. However, I encountered a problem when I upgraded to jQuery 1.8. Specifically, issues aro ...

difficulty with displaying the following image using jquery

I have referenced this site http://jsfiddle.net/8FMsH/1/ //html $(".rightArrow").on('click',function(){ imageClicked.closest('.images .os').next().find('img').trigger('click'); }); However, the code is not working ...

The request to localhost resulted in a 404 error, indicating that the resource was not found

When attempting a file upload operation using MV.Net, I encountered the GET http://localhost:55298/Home/test2.json 404 (Not Found) error while trying to upload a file. How can this issue be resolved? <input type="file" name="file" ...

I am unable to align the image in the center, what could be causing it not to center properly?

Why does my code center in mobile view but not in Desktop? How can I solve this issue? I have tried using display: block; margin: auto; width:100%; and text-align: center;, but it did not work. let $slides, interval, $selectors, $btns, currentIndex, ne ...

Trouble arises when attempting to incorporate the Restangular dependency with Angular using browserify

I've been using browserify to manage my angular dependencies successfully, however, when I try to add restangular I encounter an error: "Uncaught Error [$injector:modulerr]". Here's a glimpse of my package.json: "browser": { "angular": "./ ...

Submit the form without displaying any output in the browser, not even in the view source code

I have a basic form that needs to be submitted multiple times, but I want the submission process to be hidden from the browser. Simply using "hidden" or "display:none" won't completely hide the form code when viewing the page source. I tried using PHP ...

Creating personalized categories with Material-UI's Autocomplete feature in a React application

I've been attempting to customize the groupings in the MUI Autocomplete component, but I haven't had any luck so far. It seems like there is no built-in solution provided by the library (I hope I'm mistaken). The first grouping can be achie ...

Looking to utilize AngularJS validation in place of the default browser validation?

I am working on a form that contains two ng-forms for input validation. I have encountered two issues with my forms. 1) I am trying to implement a minlength validation for the Company input, but my current approach doesn't seem to be working. How can ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Possibility for using navigator.GetUserMedia in Internet Explorer

How can I access a webcam through JavaScript/jQuery? I have successfully opened the webcam in Chrome and Mozilla, but the navigator.GetUserMedia feature does not work in Internet Explorer. Is there a way to achieve this with JavaScript or jQuery in IE? ...