如何延迟一个函数,直到另一个函数在JavaScript中执行?

时间:2017-11-10 21:12:47

标签: javascript callback promise

我正在尝试编写一个简单的注册函数。在尝试验证用户电子邮件是否已存在时,我一直绊倒。我认为我的问题与异步性有关。我的意图是隐藏注册div并在从服务器收到201共鸣后显示配置文件div。但是,我相信在收到回复之前我的警报会不断出现。在handlePost完成之后,如何才能冻结代码?我已经通过以下方式尝试了它:

1

registerButton.onclick = function(){
  var encodedBody = getRegistrationData();
  //if encodedbody then handlepost and show profile etc
  if (encodedBody) {
    var response = handlePost(encodedBody, 'user');
    if (response == '201') {
      hideRegistration();
      showProfile();
      showLoginNav();
      showLogin();
      // clearFields() need to create this
    } else {
      alert("Invalid password or email")
      console.log('hmm')
    }
  } else {
    alert("Invalid password or email")
  }
};

2

registerButton.onclick = function() {

  var a = function(callBack){
    var encodedBody = getRegistrationData()
    var response = handlePost(encodedBody, 'user')
    callBack(response)
  }

  var b = function(response) {
    if (response == '201') {
      hideRegistration();
      showProfile();
      showLoginNav();
      showLogin();
    } else {
      alert("Invalid password or email")
    }
  }
  a(b)
}

3

registerButton.onclick = function() {
  var encodedBody = getRegistrationData()
  if (encodedBody) {
    handlePost(encodedBody, 'user').then(function(response) {
      if (response == '201') {
        hideRegistration();
        showProfile();
        showLoginNav();
        showLogin();
      } else {
        alert("Invalid password or email")
      }
    })
  } else {
    alert("Invalid password or email")
  }
};

以上功能如下:

function getRegistrationData() {
  var newUserEmail = document.querySelector("#newUserEmail");
  var newUserPassword = document.querySelector("#newUserPassword");
  var newUserPasswordVerify = document.querySelector('#newUserPasswordVerify');
  flag = []
  //verify passwords match
  if (newUserPassword.value != newUserPasswordVerify.value) {
    flag = false
    return flag
  } else {
    flag = true
  }
  //if user does not exist and passwords match return encoded body
  if (flag == true) {
    var encodedBody = 'email='+encodeURIComponent(newUserEmail.value)+'&'+'encryptedPassword='+encodeURIComponent(newUserPassword.value)
    return encodedBody
  }
};

function handlePost(encodedBody, flag) {
  if (flag =='user') {
    fetch('http://localhost:8080/users', {
      body: encodedBody,
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain',
      }
    })
    .then(function(response) {
      console.log(response.status)
      return response.status
      // clearRegistrationFields();
      // function to get user profile data
    })

  }
};

提前致谢

克里斯

1 个答案:

答案 0 :(得分:0)

你的handlPost是异步的,所以如果你想等待结果,你应该返回一个承诺:

function handlePost(encodedBody, flag) {
  return new Promise(function(resolve, reject) {
    if (flag =='user') {
    fetch('http://localhost:8080/users', {
      body: encodedBody,
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain',
      }
    })
    .then(function(response) {
      console.log(response.status)
      resolve(response.status)
      // clearRegistrationFields();
      // function to get user profile data
    })

  }
});

}

现在您的代码段3将起作用,响应对象将是handlePost承诺中解决的'response.status'。

注意:您还应该处理承诺失败。我会让你去解决这个问题。