我有以下内容。
var lookupInit = function () {
http.get('api/employmenttype', null, false)
.done(function (response) {
console.log('loaded: employmenttype');
vm.lookups.allEmploymentTypes(response);
});
http.get('api/actionlist', null, false)
.done(function (response) {
console.log('loaded: actionlist');
vm.lookups.allActionListOptions(response);
});
http.get('api/company', null, false)
.done(function (response) {
console.log('loaded: company');
vm.lookups.allCompanies(response);
});
//... x 5 more
return true;
};
// somewhere else
if (lookupInit(id)) {
vm.userInfo.BusinessUnitID('0');
vm.userInfo.BuildingCode('0');
if (id === undefined) {
console.log('api/adimport: latest');
http.json('api/adimport', { by: "latest" }, false).done(viewInit);
}
else if (id !== undefined) {
console.log('api/adimport: transaction');
http.json('api/adimport', { by: "transaction", TransactionId: id }, false).done(viewInit);
}
} else {
console.log('User info init failed!');
}
以下“http.get('api/employmenttype', null, false)”表示我将异步设置为 false。 我知道这可能效率低下。我想同时加载所有调用。 唯一的问题是,如果我没有将它们设置为 async false,我的代码的第二部分可能会在填充下拉列表之前执行。
我已经用 Jquery Deferreds 尝试了几次,但它们导致了我只能描述为流产的结果。
我唯一想要实现的是查找调用在我的代码的 adimport/second 部分之前以任何顺序完成......但是让每个调用等待它完成之前的调用 EG:async ,似乎是我能够正确实现 ATM 的唯一解决方案。
这是延迟函数的合适位置吗,谁能指出我可以弄清楚如何正确实现它的方向,因为我以前从未这样做过?
最佳答案
您可以使用 $.when
将多个 promise 合并为一个 promise ,当所有 promise 都已实现时解决。如果我没听错,你想要
function lookupInit() {
return $.when(
http.get('api/employmenttype').done(function (response) {
console.log('loaded: employmenttype');
vm.lookups.allEmploymentTypes(response);
}),
http.get('api/actionlist').done(function (response) {
console.log('loaded: actionlist');
vm.lookups.allActionListOptions(response);
}),
http.get('api/company').done(function (response) {
console.log('loaded: company');
vm.lookups.allCompanies(response);
}),
// … some more
);
}
然后在别的地方
lookupInit(id).then(function(/* all responses if you needed them */) {
vm.userInfo.BusinessUnitID('0');
vm.userInfo.BuildingCode('0');
if (id === undefined) {
console.log('api/adimport: latest');
return http.json('api/adimport', {by:"latest"})
} else {
console.log('api/adimport: transaction');
return http.json('api/adimport', {by:"transaction", TransactionId:id});
}
}, function(err) {
console.log('User info init failed!');
}).done(viewInit);
关于javascript - Jquery 延迟。多个 ajax 调用。延迟与异步假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17699709/