我有一个包含三个选择选项的菜单。第一个选择是其余两个的驱动程序;它们需要填充第一个菜单项的值。然而,它们是并行的——这两者都不依赖于彼此,因此它们的 ajax 调用可以并行运行。
我当前的步骤对第一个菜单进行 ajax 调用,然后使用 .then() 方法对下一个菜单进行调用,并使用另一个 .then() 方法对最后一个菜单进行调用。这不是很有效。我试图弄清楚如何让两个子菜单调用在一个 .then() 下运行
//Get campus list and build menu
$.getJSON(apiURL)
.then( function(campusdata) {
buildMenu('campus', campusdata);
return $.getJSON(apiURL + '/colleges/' + $campus.val());
})
//Build college menu
.then(function(collegedata) {
buildMenu('college', collegedata);
return $.getJSON(apiURL + '/campus-year-terms/' + $campus.val());
})
//Build academic terms submenu
.then(function(termdata){
buildMenu('term', termdata);
})
.done(function(){
<other stuff that can really be completeduntil menus are populated>
})
.fail(console.log.bind(console));
最佳答案
您应该使用Promise.all
$.getJSON(apiURL)
.then( function(campusdata) {
buildMenu('campus', campusdata);
// use `Promise.all` to run two parallel ajax calls
return Promise.all([
$.getJSON(apiURL + '/colleges/' + $campus.val()),
$.getJSON(apiURL + '/campus-year-terms/' + $campus.val())
]);
})
// result will be an array containing the json data from both calls
.then(function(result) {
buildMenu('college', result[0]);
buildMenu('term', result[1]);
})
.done(function(){
<other stuff that can really be completeduntil menus are populated>
})
.fail(console.log.bind(console));
关于JavaScript 延迟对象 - 在 Promise 之后运行两个异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182111/