2017-08-24 40 views
2

考虑以下代码,就像一个玩具例子:如何在一个回调函数执行后才调用一段代码?

function loadDoc() { 

    var xhttp = new XMLHttpRequest(); 

    xhttp.onreadystatechange = function() { 

     if (this.readyState == 4 && this.status == 200) { 
      document.getElementById("demo").innerHTML = this.responseText; 
     } 
    }; 
    xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true); 
    xhttp.send(); 
} 

我们认为有五种功能loadDoc()里面异步调用的。我现在想要做的是在执行所有五个回调函数时调用另一个函数或任何一段代码。 Javascript是否提供了任何帮助解决这种情况的方法,或者我们需要设置一个标志来检查是否所有5个任务都被执行了?

+0

很多在这里建议:https://stackoverflow.com/search?q=%5Bjavascript%5D+wait+multiple+ajax+-%5Bjquery%5D –

回答

0

您可以使用回调或承诺,

回调例如:

function loadDoc(cb) { 

    var xhttp = new XMLHttpRequest(); 

    xhttp.onreadystatechange = function() { 

    if (this.readyState == 4 && this.status == 200) { 
     document.getElementById("demo").innerHTML = this.responseText; 
     cb(xhttp.responseText); // <= run the callback 
    } 
    }; 
    xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true); 
    xhttp.send(); 

} 

loadDoc(function(res) { 
    console.log(res); 
    // do something 
}); 

承诺例如:

function loadDoc(cb) { 
    return return new Promise(function (resolve, reject) { 
    var xhttp = new XMLHttpRequest(); 

    xhttp.onreadystatechange = function() { 

     if (this.readyState == 4 && this.status == 200) { 
     document.getElementById("demo").innerHTML = this.responseText; 
     resolve(xhttp.responseText); // <= run the callback 
     } else { 
     reject(xhttp.responseText); 
     } 
    }; 
    xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true); 
    xhttp.send(); 

} 

loadDoc() 
.then(function(res) { 
    console.log(res); 
    // do something 
}) 
.catch(function(err) { 
    console.error(err); 
    // do something 
}); 
+3

回调一定不能在'loadDoc'的底部调用,那么它就没用了。它应该在'onreadystatechange'的回调中被调用。 –

+0

感谢您纠正我,我已经更新了我的答案。 –

2

如果使用promises你就可以使用Promise.all([promises])

“Promisifying” 当前的Ajax请求:

function loadDoc() { 
    req().then(function (responseText) { 
     document.getElementById("demo").innerHTML = responseText; 
    }) 

} 

function req() { 
    return new Promise(function (resolve, reject) { 
     var xhttp = new XMLHttpRequest(); 

     xhttp.onreadystatechange = function() { 

      if (this.readyState == 4 && this.status == 200) { 
       resolve(this.responseText); 
      } else { 
       reject(); 
      } 
     }; 
     xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true); 
     xhttp.send(); 
    }); 
} 
相关问题