You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Toastr的JS删除确认弹窗无法返回布尔值问题求助

解决Toastr删除确认弹窗无法返回布尔值的问题

问题根源

你的代码里有两个关键问题导致拿不到预期的返回值:

  1. fileAlert函数没有返回一个Promise,所以你用await的时候根本等不到用户的选择结果
  2. 按钮点击回调里的return userSaid只是回调自身的返回值,完全传不到函数外部,更没法成为你要的最终结果

修改后的完整代码

我把你的逻辑重新用Promise封装了一遍,现在可以正确获取用户的选择:

function fileAlert() {
  // 让函数直接返回Promise,把用户交互逻辑包裹在里面
  return new Promise((resolve) => {
    var userAnswer = toastr.warning(
      'Are you sure you want to delete the file?<br /><br /><button type="button" id="yesDelete" class="btn clear">Yes</button>&nbsp;<button type="button" id="noDelete" class="btn clear">No</button>',
      "Warning"
    );

    toastr.options = {
      "closeButton": false,
      "allowHtml": true,
      onShown: function (toast) {
        $('#yesDelete').click(function () {
          console.log('user clicked yes - he wants to delete the file')
          toastr.clear(userAnswer);
          // 通知Promise:用户选择了确认
          resolve(true);
        });
        $('#noDelete').click(function () {
          console.log('user clicked no - he doesnt want to delete the file')
          toastr.clear(userAnswer);
          // 通知Promise:用户选择了取消
          resolve(false);
        });
      },
      "debug": false,
      "newestOnTop": false,
      "progressBar": false,
      "positionClass": "toast-top-right",
      "preventDuplicates": false,
      "showDuration": "300",
      "hideDuration": "1000",
      "timeOut": 0,
      "extendedTimeOut": 0,
      "showEasing": "swing",
      "hideEasing": "linear",
      "showMethod": "fadeIn",
      "hideMethod": "fadeOut",
      "tapToDismiss": false
    };
  });
}

// 调用逻辑也可以简化
async function noticeUser() {
  let result = await fileAlert();
  console.log("The result was: " + result); // 现在会正确输出true或false
}

关键修改说明

  • 让fileAlert直接返回Promise:这是异步获取用户交互结果的标准方式,Promise会等待用户点击后才会完成
  • 用resolve()传递结果:按钮点击时不再用无效的return,而是调用resolve()把用户的选择(true/false)传递给外部的await
  • 简化调用逻辑:不需要自己再额外封装一层Promise,直接await fileAlert()就能拿到结果

这样修改后,你调用noticeUser()就能正确获取用户点击Yes/No对应的布尔值了。

内容的提问来源于stack exchange,提问作者Noah Ko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:37:33