Reputation: 31
I have an array of 'projects' containing the project owner id, and the project's title.
I want to get each project's owner name by looping through the 'projects' array, and making a request call, passing each project 'owner id', to some server using 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);
});
});
I want to abort / not calling the ajax function when the project iteration is the "Second project by id one" because I would have gotten the data when the iteration was "First project by id one".
That is to say, I want to output this (assume owner_id 1,2,3, is Alice, Bob and Charlie respectively):
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
But instead, I got this:
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
How could I achieve this while maintaining the asynchronousity (without using "async=false") in AJAX?
Upvotes: 0
Views: 174
Reputation: 119837
What you're looking for is Promise.race
. However, to do what you're asking, you'll need to group up the data by owner ID first and pass them to Promise.race
. Do this for every owner that has multiple projects.
// Something like...
Promise.all([
Promise.race([ owner1project1ajax, owner1project2ajax ]),
owner2project1ajax,
owner3project1ajax,
])
Note that while $.when
is the jQuery equivalent for Promise.all
, there is no jQuery equivalent for Promise.race
. Also it won't abort the other promises, but will resolve with the value of the promise that resolves/rejects first, ignoring the rest.
Upvotes: 1