Sweet Alert 2 и Socket.io используют результат emit в preConfirm - PullRequest
0 голосов
/ 12 января 2019

Я использую SWAL2 preConfirm () в приятном предупреждении, чтобы проверить, в порядке ли ID на стороне сервера ... используя socket.emit() с подтверждениями

Я хотел бы иметь возможность использовать Swal.showValidationMessage("Some error") в зависимости от возвращенной ошибки сервера ...

Но функция preConfirm работает только с функциями обещаний, что означает использование .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>

РЕДАКТИРОВАТЬ Bump

Ответы [ 2 ]

0 голосов
/ 28 мая 2019

С помощью @ 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>
0 голосов
/ 20 мая 2019

Вы можете использовать другую пользовательскую функцию обещания, которая вызывает 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'
      });
  }
})

Надежда помогает.

...