我正在编写一些 Javascript/jQuery 代码,需要我向各种 API 发出大量请求。我多次遇到过这个问题,这只是其中一个实例的基本示例。
代码向服务器发出异步请求,然后如果不满足返回数据的条件,则代码发出另一个请求。第二个请求有一个回调,其中包含许多与其父请求相同的逻辑。我知道我通过在每个回调中调用 returnFunction
来避免重复,但有没有办法完全避免这种情况?
var container = [];
$.getJSON("http://www.url.com/api/?callback=?",
{ data: "mydata" },
function(data) {
if(!data.length) {
// No results
} else {
// Put the results into an array
$(data).each(function(k, v){
container.push(v.some_data);
});
// If the query did not return enough results
if(data.length < limit) {
var number_missing = limit - data.length;
// Get some more results and append to the array
myFunctionToGetSomethingElse(number_missing, function(response){
// Add these results to the array
$(response).each(function(k, v){
container.push(v.some_data);
});
// Do something with this data
returnFunction(response);
});
} else {
// Do something with the result
returnFunction(data);
}
}
});
您建议我如何避免回调中的代码重复?这是唯一可行的方法吗?
最佳答案
// <script src="http://code.onilabs.com/0.9.1/oni-apollo.js"></script>
// <script type="text/sjs">
// install stratified versions of jquery functions; see below
require('jquery-binding').install();
// Note the extra '$' in $getJSON. This is the 'stratified' version of
// getJSON. Instead of taking a callback it blocks until the result is
// available. The browser will stay responsive during that time.
var data = $.$getJSON("http://www.url.com/api/?callback=?", {data: "mydata"});
if (!data.length) {
// no results
} else {
$(data).each(function(k, v){
container.push(v.some_data);
});
if (data.length < limit) {
var number_missing = limit - data.length;
// assuming your function 'myFunctionToGetSomethingElse' uses
// something like $.$getJSON inside, again you don't need a
// callback
$(myFunctionToGetSomethingElse(number_missing)).each(
function(k, v){
container.push(v.some_data);
});
}
}
// console.log(container);
// do something with the result. E.g. call returnFunction() or put the
// code from returnFunction here directly
您可以在 http://onilabs.com/apollo 上获得更多信息
关于javascript - 使用回调函数和异步请求时避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3768552/