Currently, I am in the process of restructuring some older code that was not originally written by me. A specific issue has arisen related to loading asynchronous data. When a particular modal is first activated, a significant amount of data representing a form object is loaded. Subsequently, a function iterates over the form inputs and populates them as needed. This is a very basic representation:
component.inputs.forEach(function(input) {
if (input.field == 'foo') {
input.cols = 5;
//more actions here
}
if (input.field == 'bar') {
DataService.getBars().then(function(data){
data.forEach(function(e){
input.options.push(e.description);
});
};
}
if (input.field == 'baz') {
input.pattern = /regex/;
//more actions here
}
});
return component;
An issue arises when the program encounters an async call to DataService within the 'bar' input section. The code proceeds to the final return statement before the Promise from DataService resolves. Consequently, upon the initial opening of the modal, the 'bar' input remains unfilled.
I am contemplating possible solutions such as making the code pause until the Promise from DataService completes or finding an alternative approach to handle situations where the function is mostly synchronous but requires an async operation in one instance. Could it be that by integrating an async call into this series of conditionals, I have inadvertently created a complication?