白板的微信
2023-09-28 15:38:07
我有一個名為 的函數sweetAlertConfirmationMessage。它接受一條消息,將其顯示為文本,然后等待用戶確認或取消彈出警報。function sweetAlertConfirmationMessage(message) { Swal.fire({ title: T('SWEETALERT_GENERAL_CONFIRMATION_TITLE'), text: message, icon: 'warning', showCancelButton: true, confirmButtonColor: T('SWEETALERT_CONFIRM_BUTTON_COLOR'), cancelButtonColor: T('SWEETALERT_CANCEL_BUTTON_COLOR'), cancelButtonText: T('SWEETALERT_CANCEL_BUTTON_TEXT'), confirmButtonText: T('SWEETALERT_CONFIRM_BUTTON_TEXT'), }) .then(result => { return new Promise(function (resolve, reject) { resolve(true); }); }) .catch(result => { console.log(result); });}我想要實現的目標如下:sweetAlertConfirmationMessage(T('SWEETALERT_MESSAGE_DELETE_PRODUCT_FROM_CART')) .then( // Run code here. )但是,我收到以下錯誤:未捕獲(承諾中)類型錯誤:無法讀取未定義的屬性“then”這是我觀察到正在發生的事情:sweetAlertConfirmationMessage 方法已運行。在 Promise 被解決之前,代碼繼續離開函數,進入 .then(// Run code here).then 沒有運行,因為它沒有承諾采取行動它顯示通知消息并等待用戶確認或取消。console.log(結果) 不顯示任何內容。我研究了以下主題:異步和等待Promise、.then 和 .catch承諾鏈如何以所需的順序執行此代碼:顯示確認消息等待承諾:如果確認則為 true,如果單擊其他任何內容則為未定義運行 .then ( // 在此處運行代碼 )我希望這個答案寫得足夠好,以幫助將來的其他人。
1 回答

森欄
TA貢獻1810條經驗 獲得超5個贊
function sweetAlertConfirmationMessage(message) {
? ? return Swal.fire({
? ? ? ? title: T('SWEETALERT_GENERAL_CONFIRMATION_TITLE'),
? ? ? ? text: message,
? ? ? ? icon: 'warning',
? ? ? ? showCancelButton: true,
? ? ? ? confirmButtonColor: T('SWEETALERT_CONFIRM_BUTTON_COLOR'),
? ? ? ? cancelButtonColor: T('SWEETALERT_CANCEL_BUTTON_COLOR'),
? ? ? ? cancelButtonText: T('SWEETALERT_CANCEL_BUTTON_TEXT'),
? ? ? ? confirmButtonText: T('SWEETALERT_CONFIRM_BUTTON_TEXT'),
? ? })
}
只需從您的函數返回承諾即可。你可以這樣使用它:
sweetAlertConfirmationMessage('msg').then(x => {})
添加回答
舉報
0/150
提交
取消