const handleEnter = (e) => {
if (e.key === 'Enter') {
const bulkSearchString = e.target.value;
const jobIdArray = bulkSearchString.split(',').map((value) => value.trim());
jobIdArray.map((jobId, i) => fetchEachJob(jobId, atsFilter.type)
.then(result => {
if (result.length) {
const value = result[0];
const index = findIndex(formValuesId, (o) => o === value.id);
if (index < 0) {
setTimeout(
() => {
addNewOption(
value,
atsFilter.filterType,
atsFilter.type,
atsFilter.radio,
true
);
},
500 * i
);
}
}
}));
e.preventDefault();
}
};
fetchEachJob: API call
addNewOption: Synchronous function
In the above code, I have added setTimeout so that addNewOption execution completes before it is called with new parameters. Without the setTimeout, the addNewOption is getting cancelled by the next call, thus returning result for only the last call. The code works fine with setTimeout but it is not the optimal solution.
Is there a way to wait for this synchronous function to finish before it is called by the next iteration?