我正在使用SWAL2 preConfirm()函数在一个甜蜜的警报中测试 ID 是否可以在服务器端...使用 socket.emit()
和 acknowledgements
我希望能够根据服务器返回的错误使用Swal.showValidationMessage("Some error")
...
但是 preConfirm 函数只能与 Promise 函数一起使用,也就是说使用 .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("")
保持甜蜜警报打开,以便稍后在服务器错误时实现它......
问题是,如果连接速度较低,即使服务器的答案是正确的,也可以看到空消息
关于如何改进这一点有什么建议吗?
(在下面的代码片段中,我使用带有超时的 promise 来模仿长服务器答案)
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 的自定义 Promise 函数,例如:
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'
});
}
})
希望有帮助。
关于javascript - Sweet Alert 2 和 Socket.io 在 preConfirm 中使用发出的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54162443/