使用 Swal 时,如何在 then 语句中获取 fetch async 的值?
How can I get the value of fetch async in then statement when I am using Swal?
这是我的源代码。我正在使用 sweetalert2.all.min.js 来使用 swal
弹出窗口。现在我有一个问题,如何从 then
语句中的 API 端点访问返回值?我也在源代码中标记了它。
这是来源:
Swal.fire({
title: 'Welcome',
text: "Enter Username and Password",
html:
'<input id="username_input" class="swal2-input" placeholder="Enter Username">',
input: 'password',
inputPlaceholder: 'Enter Password',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: false,
confirmButtonText: 'Login',
showLoaderOnConfirm: true,
preConfirm: (passwordEntered) => {
var usernameEntered = document.getElementById('username_input').value;
return fetch("...my_endpoint.../checkusername/" + usernameEntered + "/" + passwordEntered)
.then(response => {
response.text().then((val) => {
return val // **: I need to get this value in * place
});
})
.catch(error => {
return "ERROR";
})
},
allowOutsideClick: () => {
!Swal.isLoading()
}
}).then((result) => {
alert(result.value); // *: I need to access the value from **
})
所以,当我记录结果值时,我得到 passwordEntered
变量的值。
通过删除 .then()
语法并切换到 async/await
:
preConfirm: async (passwordEntered) => {
var usernameEntered = document.getElementById('username_input').value;
const response = await fetch("...my_endpoint.../checkusername/" + usernameEntered + "/" + passwordEntered);
return await response.text();
},
这是我的源代码。我正在使用 sweetalert2.all.min.js 来使用 swal
弹出窗口。现在我有一个问题,如何从 then
语句中的 API 端点访问返回值?我也在源代码中标记了它。
这是来源:
Swal.fire({
title: 'Welcome',
text: "Enter Username and Password",
html:
'<input id="username_input" class="swal2-input" placeholder="Enter Username">',
input: 'password',
inputPlaceholder: 'Enter Password',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: false,
confirmButtonText: 'Login',
showLoaderOnConfirm: true,
preConfirm: (passwordEntered) => {
var usernameEntered = document.getElementById('username_input').value;
return fetch("...my_endpoint.../checkusername/" + usernameEntered + "/" + passwordEntered)
.then(response => {
response.text().then((val) => {
return val // **: I need to get this value in * place
});
})
.catch(error => {
return "ERROR";
})
},
allowOutsideClick: () => {
!Swal.isLoading()
}
}).then((result) => {
alert(result.value); // *: I need to access the value from **
})
所以,当我记录结果值时,我得到 passwordEntered
变量的值。
通过删除 .then()
语法并切换到 async/await
:
preConfirm: async (passwordEntered) => {
var usernameEntered = document.getElementById('username_input').value;
const response = await fetch("...my_endpoint.../checkusername/" + usernameEntered + "/" + passwordEntered);
return await response.text();
},