我正在寻找一种让这组AJAX调用变得更干净的方法。我尝试过使用$.when()
...但我无法真正开始工作。我认为这是由于没有传递延迟对象......因为我的AJAX调用是在模型对象中。
这是我到目前为止(一些代码被排除在外):
var origin_form, destination_form; //assume string input from user
var destination, origin;
getOrigin();
//Gets origin data
function getOrigin(){
//ASYNC CALL
model.searchFeature(origin_form, 1, function(data){
//additional callback code excluded
origin = data;
getDestination();
});
}
//Gets destination information
function getDestination(){
//ASYNC CALL
model.searchFeature(destination_form, 1, function(data){
//additional callback code excluded
destination = data;
directions(origin, destination);
});
}
function directions(origin, destination){
//Async call to request directions from google api
}
任何建议都会很棒!
编辑:我正在寻找类似于$.when()
的解决方案。基本上,我希望在directions()
和getOrigin()
完成后调用getDestination()
而不进行嵌套回调。
答案 0 :(得分:1)
不要在共享范围中使用变量,只需传递从函数到函数的值。
var origin_form, destination_form; //assume string input from user
getOrigin();
function getOrigin(){
model.searchFeature(origin_form, 1, getDestination);
}
function getDestination(origin){
model.searchFeature(destination_form, 1, function(data) {
directions(origin, data);
});
}
function directions(origin, destination){
//Async call to request directions from google api
}
或者使用Function.prototype.bind
,您可以将其清理一下。
var origin_form, destination_form; //assume string input from user
getOrigin();
function getOrigin(){
model.searchFeature(origin_form, 1, getDestination);
}
function getDestination(origin){
model.searchFeature(destination_form, 1, directions.bind(null, origin));
}
function directions(origin, destination){
//Async call to request directions from google api
}
传递给.bind()
的第一个参数是null
,因为我不知道您是否希望设置this
的{{1}}值。如果您这样做,请将directions()
替换为您想要的null
。
答案 1 :(得分:1)
上面的回答是user1689607给出了一个很好的建议,如何改进 回调安排。
我认为你可以进一步改进这个代码,而不仅仅是制作 然而,回调更清洁。首先,使用camel case和jslint,然后:
// Use a closure/namespace for global abatement
MyNamespace = (function() {
// Use a single 'var' declaration
var originForm,
destinationForm, //assume string input from user
destination,
origin;
function init() {
getOrigin();
}
//Gets origin data
function getOrigin(){
//ASYNC CALL
model.searchFeature(origin_form, 1, function(data){
//additional callback code excluded
destination = data;
getDestination();
});
}
//Gets destination information
function getDestination(){
//ASYNC CALL
model.searchFeature(destinationForm, 1, function(data){
//additional callback code excluded
destination = data;
directions(origin, destination);
});
}
function directions(origin, destination){
//Async call to request directions from google api
}
return {
'init': init
};
}());
MyNamespace.init();