首先运行javascript es6回调

时间:2017-02-16 15:53:52

标签: callback ecmascript-6

我构建了以下事件监听器,它将运行函数isValidEmail,传入一个回调函数NotInDatabase(),该函数计划仅在ajax调用完成后运行。尽管NotInDatabase()会立即运行。知道为什么会这样吗?

事件监听器:

const bindEvents = (form, inputSelector, errorSelector) => {
   const emailInput = document.getElementById('email');
   emailInput.addEventListener('blur', function(){
     const emailValue = emailInput.value
     isValidEmail('http://localhost:3001/user/email/'+emailValue,'data_placeholder', NotInDatabase())
   });
}

isValidEmail with callback:

const isValidEmail = (url, data, success) => {
  const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  xhr.open('POST', url);
  xhr.onreadystatechange = function() {
    if (xhr.readyState>3 && xhr.status==200) {
      success(xhr.responseText);
    }
  };
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin');
xhr.send(data);
return xhr;
}

1 个答案:

答案 0 :(得分:1)

这里

isValidEmail('http://localhost:3001/user/email/'+emailValue,'data_placeholder', NotInDatabase())

您没有将NotInDatabase函数作为回调传递到isValidEmail,而是传递它返回的内容,因为NotInDatabase()是一个函数调用。

删除()以解决您的问题