Home > database >  call multiple async functions in sequential order
call multiple async functions in sequential order

Time:03-17

async function unsubscribeUserHandler() {
  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 deleteUserHandler() {
  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 deleteAccount = async () => {
    try {
        await unsubscribeUserHandler();
        await deleteUserHandler();
    } catch (err) {
        console.error('ERROR@@@@@!!!',err);
    }
}

const Settings = () => {
  return <DeleteAccount onDeleteAccount={deleteAccount} />;
};

As shown here, I want to unsubscribe.. only after the unsub, then run delete handler.

I have issues where It only runs one of the handlers and not the other. Are there other ways to do this?

have tried:

.then(() => deleteUserHandler())

and

.then(deleteUserHandler)

above doesn't make call to /api/user/delete-account,

only to unsubscribe.

CodePudding user response:

This is wrong:

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

You aren't passing deleteUserhandler to then(), you are immediately calling it and pass the result to then().

To fix, lose the parenthesis:

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

Or use an arrow function:

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

Or better yet:

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