javascript - 循环内的 AJAX 请求 : aborting certain ajax call based on the response of the previous call?

标签 javascript jquery ajax asynchronous event-loop

我有一个“项目”数组,其中包含项目所有者 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,
])

请注意,虽然 $.whenPromise.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/

相关文章:

jquery - 长时间运行任务的 Grails 状态更新

javascript - 使用 javascript 迭代 json 数据的通用函数?

javascript - 如何在 window.onload 事件后使用 reactjs/nextjs 加载脚本

javascript - 当用户单击一个选项时,用勾号或 html 中的任何内容标记它

javascript - jQuery 手机 : How To Put Listview Popup on Top of Page Content?

php - Ajax PHP 实时搜索 - 需要第二步

javascript - 需要帮助使用简单的数据网格让多个表在单个页面上工作

jquery - 如何覆盖引导元素的默认内容?

javascript - ajax调用不显示上传图片

jquery - 从安全网络服务获取图像