I'm having some trouble with a function that returns before ajax call from for loop ends. I do several ajax call which I get the result from and use them on my then chain.
Here is my code
const delay = t => new Promise(resolve => setTimeout(resolve, t));
(async () => {
await delay(timeout);
let results: boolean[] = [];
for (let i = 0; i < times; i++) {
await this.ajaxService.postWithData("/api/v1/..",
arg,
(data) => {
results[i] = this.checkStep(data);
},
() => {
});
}
return results; // This returns before for loop containing ajaxServces calls ends
})().then((results) => {
// Do some things here using `results`
});
postWithData
public request = (options: Options, successCallback: Function, errorCallback?: Function): void => {
var that = this;
$.ajax({
url: options.url,
type: options.method,
data: options.data,
cache: false,
success: function (d) {
successCallback(d);
},
error: function (d) {
if (errorCallback) {
errorCallback(d);
return;
}
}
});
}
I've checked SO answers, e.g. https://stackoverflow.com/a/40329190/3264998