У меня есть следующий код, где я сталкиваюсь с рядом проблем, которые, я полагаю, связаны.Я не могу использовать await
при вызове функции из-за получения этой ошибки SyntaxError: await is only valid in async functions and async generators
.
Что еще более важно, мой второй ajax
вызов (функция saveTokenToUser
), похоже, не выполняется вообще.
Я пытаюсь сделать следующее:
- onClick of login button - отправить данные для подтверждения.
- В случае успеха также отправьте токен (если он предоставляется через строку запроса) на сервер, который будет сохранен для этого нового пользователя.
- Перенаправление на пользовательскую страницу.
- если не удалось войти в систему, перезапустите форму и отобразите соответствующие сообщения.
Благодарю TJ Crowder, который уже очень помог.
При успешном входе в систему будет возвращен текст в формате good|4
(поэтому я проверяю, чтобы первые 4 символа были good
)
КОД:
// this code saves the token
var saveTokenToUser = (tokenViaApp) => {
return $.ajax("/includes/notifications/ajax_save_user_token", {
data: {
t: tokenViaApp
},
}).done((response) => {
console.log('Done ', response)
}).fail(error => {
console.log('Error ', error)
})
.always(response => {
console.log('always ', response)
}).then(response => {
console.log('successfully sent in function');
localStorage.token_origin = 'app';
})
} // end function
// this code verifies login details:
var checkLogin = async (semail, spass, scaptcha, stokenViaApp) => {
console.log('Checking login')
return $.ajax("/users/ajax_login", {
data: {
email: semail,
pass: spass,
captcha: scaptcha
},
}).done((response) => {
console.log('Done ', response)
}).fail(error => {
console.log('Error ', error)
})
.always(response => {
console.log('always ', response)
}).then(msg => {
console.log('login response: ' + msg);
if (msg==='notfound') {
$("#LoginMessage").html('The user does not exist in the system').addClass("alert alert-danger");
grecaptcha.reset();
} else if (msg==='captcha') {
$("#LoginMessage").html('Are you a robot <i class="fa fa-smile-o" aria-hidden="true"></i>').addClass("alert alert-danger");
} else if (msg==='bad') {
$("#LoginMessage").html('The password is incorrect').addClass("alert alert-danger");
grecaptcha.reset();
} else if (msg==='pass') {
$("#LoginMessage").html('Please enter with your password').addClass("alert alert-warning");
$("#password").removeClass("hidden");
grecaptcha.reset();
} else if (msg.substring(0,4)==='good') {
console.log('token is: ' + stokenViaApp);
// login was successful, lets see if a token exists, and then save it:
if (stokenViaApp !==''){
console.log("Starting to save token script ");
var TokenResponse = saveTokenToUser(stokenViaApp); // tried 'await' here but generated error: SyntaxError: await is only valid in async functions and async generators
}
// all is good, let's redirect:
window.location = '/users/default_forwarder.asp';
}
return msg;
})
} // end function
$("#submitter").click(function(e){
e.preventDefault();
var email = $("#email").val();
var pass = $("#entry").val();
var captcha = $("#g-recaptcha-response").val();
$("#LoginMessage").html('').removeAttr('class');
$("#submitter").val('Checking...');
// check for token:
var tokenViaApp = $.urlParam('t')
if (tokenViaApp == false ) {
tokenViaApp = ''
}
// send to login function:
var loginResponse = checkLogin(email, pass, captcha, tokenViaApp); // tried 'await' here but generated error: SyntaxError: await is only valid in async functions and async generators
$("#submitter").val('Login'); // reset form
}); // on login click
ЭТО ЖУРНАЛ КОНСОЛИ:
Checking login
XHRGET /users/ajax_login?email=...&pass=1234&captcha....
Done good|2
always good|2
login response: good|2
token is: 333333
Starting to save token script
>> and then a redirect. instead of calling the code to save the token and THEN doing the redirect
Нет никакого вызова ajax для сохранения токена, хотя у меня есть токен в URL, и, как вы можете видеть,код видит его.
Итак, мой вопрос: почему 2-я функция не была успешно вызвана или ожидала?
Спасибо.