按顺序调用多个异步函数
2022-03-16
2514
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} />;
};
如此处所示,我想取消订阅.. 仅在取消订阅后,然后运行删除处理程序。
我遇到的问题在于它仅运行其中一个处理程序而不运行另一个。还有其他方法可以做到这一点吗?
已尝试:
.then(() => deleteUserHandler())
和
.then(deleteUserHandler)
以上不调用 /api/user/delete-account,
仅取消订阅。
1个回答
这是错误的:
const deleteAccount = () => unsubscribeUserHandler()
.then(deleteUserHandler())
.catch(console.error);
您没有将
deleteUserhandler
传递给
then()
,而是立即调用它并将结果传递给
then()
。
要修复,请删除括号:
const deleteAccount = () => unsubscribeUserHandler()
.then(deleteUserHandler)
.catch(console.error);
或者使用箭头函数:
const deleteAccount = () => unsubscribeUserHandler()
.then(() => deleteUserHandler())
.catch(console.error);
或者更好的是:
const deleteAccount = async () => {
try {
await unsubscribeUserHandler();
await deleteUserHandler();
} catch (err) {
console.error(err);
}
}
Evert
2022-03-17