在Ajax上使用异步和等待功能

时间:2019-06-11 02:12:30

标签: jquery ajax async-await

我有以下代码,遇到了一些我认为与之相关的问题。由于出现此错误await,我在调用功能时无法使用SyntaxError: await is only valid in async functions and async generators

更重要的是,我的第二个ajax调用(saveTokenToUser函数)似乎根本没有运行。

我想做的是:

    点击登录按钮的
  1. -发送登录详细信息以进行验证。
  2. 如果成功,还发送令牌(如果通过查询字符串提供) 到要为此新用户保存的服务器上。
  3. 重定向到基于用户的页面。
  4. 如果登录失败,请保留表格并显示相应的消息。

谢谢T.J.拥挤者已经很有帮助。

成功登录后将以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

即使我在URL中有一个令牌,也没有一个ajax调用来保存令牌,正如您所看到的那样,代码正在查看它。

所以-我的问题是为什么第二个函数没有成功调用或等待?

谢谢。

0 个答案:

没有答案