Sweet Alert 2 和 Socket.io 在 preConfirm 中使用 emit 的结果

Sweet Alert 2 and Socket.io use result of an emit in preConfirm

我正在使用 SWAL2 preConfirm() function in a sweet alert to test if an ID is ok server side... using socket.emit() with acknowledgements

我希望能够使用 Swal.showValidationMessage("Some error") 取决于服务器返回的错误...

但是 preConfirm 函数只适用于 promises 函数,意思是使用 .then().catch()...

我找到的唯一解决方法是一个丑陋的解决方法:

 Swal.fire({
  title: 'ID ?',
  input: 'text',
  showCancelButton: true,  
  confirmButtonText:'Go',
  cancelButtonText: "Cancel",
  showLoaderOnConfirm: true,
  preConfirm: (id) => {
    if(id.trim().length === 3){
      socket.emit('isID', id, this.props.name, (r) => {

        // Here I have the answer from the server so I can test the returned
        // value and eventualy set an error which I couldn't if I didn't put the "TRICK" part ( see below )
        if(r === 'ok'){
          Swal.fire({
            title: `ok !!`,
            type: 'success'
          });
        } else {
           Swal.showValidationMessage("Server error !");
        }
      });

      Swal.showValidationMessage(""); // --> HERE IS THE 'TRICK'

    } else {
      Swal.showValidationMessage(" it's 3 letters for an id mate !");
    }
  },
});

让我解释一下:使用 Swal.showValidationMessage("") 保持甜蜜警报打开,以便稍后在服务器错误时实现它...

问题是如果连接低,即使服务器的回答是正确的,也可以看到空消息

关于如何改进这个的任何建议?

(在下面的代码片段中,我使用带有超时的承诺来模拟长服务器响应)

Swal.fire({
      title: 'ID ?',
      input: 'text',
      showCancelButton: true,  
      confirmButtonText:'Go',
      cancelButtonText: "Cancel",
      showLoaderOnConfirm: true,
      preConfirm: (id) => {
        if(id.trim().length === 3){
          let r = new Promise(function(resolve, reject) {
            setTimeout(function() {
              Swal.fire({
                title: `Server answered OK no need to error message !`,
                type: 'success'
              });
            }, 2000);
          });
       
          Swal.showValidationMessage(""); // --> HERE IS THE 'TRICK'
            
        } else {
          Swal.showValidationMessage(" it's 3 letters for an id mate ;)");
        }
      },
    });
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8.0.7/dist/sweetalert2.all.min.js"></script>

编辑 凹凸

您可以使用另一个调用 socket.emit 的自定义承诺函数,例如:

emit(event, data,prop) {
   return new Promise((resolve, reject) => {
       if (!this.socket) {
           reject('No socket connection.');
       } else {
           this.socket.emit(event, data, prop, (response) => {
              resolve(response);
           });
       }
   });
 }

然后你的代码将是这样的:

Swal.fire({
  title: 'ID ?',
  input: 'text',
  showCancelButton: true,  
  confirmButtonText:'Go',
  cancelButtonText: "Cancel",
  showLoaderOnConfirm: true,
  preConfirm: (id) => {
    if(id.trim().length === 3){
      return emit('isID', id, this.props.name)
      .then((r) => {
        if(r === 'ok'){
          return r;
        } else {
           Swal.showValidationMessage("Server error !");
        }
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
    } else {
      Swal.showValidationMessage(" it's 3 letters for an id mate !");
    }
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.value) {
    Swal.fire({
        title: `ok !!`,
        type: 'success'
      });
  }
})

希望有所帮助。

在@Mike85 的帮助下,这是有效的方法:

const gonnaWork = false;
const promiseWrapper = (id) => {
   return new Promise((resolve, reject) => {
       //this.socket.emit(id, data, data2, (response) => {
       //   resolve(response);
       //});
       setTimeout(function() {
          resolve(gonnaWork ? 'ok' : 'ko');
       }, 2000);
   });
}

Swal.fire({
  title: 'ID ?',
  input: 'text',
  showCancelButton: true,  
  confirmButtonText:'Go',
  cancelButtonText: "Cancel",
  showLoaderOnConfirm: true,
  preConfirm: (id) => {
    if(id.trim().length === 3){
      return promiseWrapper(id)
      .then((r) => {
        if(r === 'ok'){
          return r;
        } else {
           Swal.showValidationMessage("Server error !");
        }
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
    } else {
      Swal.showValidationMessage(" it's 3 letters for an id mate !");
    }
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.value) {
    Swal.fire({
        title: `ok !!`,
        type: 'success'
      });
  }
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8.0.7/dist/sweetalert2.all.min.js"></script>