Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6.
Let's imagine we have an array of objects:
[{ Object }, { Object}, { Object }]
I want to iterate over each object in the array, make a call to an API with a specific parameter from the object, receive the response, and then proceed to make another call to the same API for the remaining objects. Essentially, I'm looking to chain these calls together sequentially and update my application state accordingly.
Here's what I've managed to put together so far, although it's not functioning as intended:
private getData(options: any[]): void {
let promises: any[] = [];
options.map((option: any, key: number) => {
let deferred: JQueryDeferred<any> = $.Deferred();
deferred.done((response) => {
return this.getIndividual(option)
.done(response => {
console.log('done', response);
});
});
promises.push(deferred);
});
$.when.apply($, promises)
.then((response) => {
console.log('response', response);
}).fail((error) => {
console.log("Ajax failed");
})
.done(() => {
console.log('done');
});
}
private getIndividual(option: any) {
return apiCall(option.hashKey);
}