我有一个“项目”数组,其中包含项目所有者 ID 和项目标题。
我想通过循环“projects”数组来获取每个项目的所有者名称,并发出请求调用,将每个项目“所有者 ID”传递到使用 AJAX 的某个服务器。
var projects = [
{owner_id: 1, title: "First project by id one"},
{owner_id: 2, title: "First project by id two"},
{owner_id: 1, title: "Second project by id one"},
{owner_id: 3, title: "First project by id three"}
];
//iterate through the 'projects' array to get the project's owner_id its respective owner_name
var owner_names = {};
projects.forEach(function(project) {
//check if the id exist in the owner_names key-value pair
if (project.owner_id in owner_names) {
//go the next iteration because we already know the owner name
return;
}
//get username by id
$.ajax({
url: '//some.com/get/owner_name/by/id/',
data: project.owner_id
}.then(function(data) {
owner_names[data.id] = data.name;
console.log("First project by " + data.name + " is " + project.title);
});
});
当项目迭代是“id one的第二个项目”时,我想中止/不调用ajax函数,因为当迭代是“id one的第一个项目”时,我会获取数据。
也就是说,我想输出这个(假设owner_id 1,2,3,分别是Alice,Bob和Charlie):
First project by Alice is First project by id one
First project by Bob is First project by id two
First project by Charlie is First project by id three
但是,我得到了这个:
First project by Alice is First project by id one
First project by Bob is First project by id two
First project by Alice is Second project by id one
First project by Charlie is First project by id three
如何在 AJAX 中保持异步性(不使用“async=false”)的同时实现这一目标?
最佳答案
您正在寻找的是 Promise.race
。但是,要执行您所要求的操作,您需要首先按所有者 ID 对数据进行分组,并将它们传递给 Promise.race
。为拥有多个项目的每个所有者执行此操作。
// Something like...
Promise.all([
Promise.race([ owner1project1ajax, owner1project2ajax ]),
owner2project1ajax,
owner3project1ajax,
])
请注意,虽然 $.when
是 Promise.all
的 jQuery 等效项,但 Promise.race
没有 jQuery 等效项。此外,它不会中止其他 promise ,但会以首先解决/拒绝的 promise 的值来解决,忽略其余的。
关于javascript - 循环内的 AJAX 请求 : aborting certain ajax call based on the response of the previous call?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047236/