As a newcomer to Javascript promises, I am encountering an issue that has proven elusive in my research through Google and Stack Exchange. It seems that when referencing a function in a .then chain off a promise, I sometimes must enclose that function within an anonymous function to prevent it from executing prematurely before the initial promise is resolved. For instance, consider the following code:
function deleteAdvertiser(advertiser) {
dialogService.Confirm(null, 'Delete')
.then(advertiserService.deleteAdvertiser(advertiser))
.then(getAdvertisers);
}
In this example, the call to advertiserService.deleteAdvertiser will execute automatically before awaiting the resolution of the dialogService.Confirm promise. However, by structuring the code as follows:
function deleteAdvertiser(advertiser) {
dialogService.Confirm(null, 'Delete')
.then(function () {
advertiserService.deleteAdvertiser(advertiser)
.then(getAdvertisers);
});
}
The functionality behaves as intended: advertiserService.deleteAdvertiser is deferred until after resolving the dialogService.Confirm promise (usually triggered by clicking the "Delete" button within the confirmation dialog).
The dialogService utilizes ngDialog's .openConfirm method, which indeed returns a promise that functions properly. My current assumption for why this scenario occurs revolves around the necessity of passing an advertiser object from the UI (typically initiated via an ng-click on a trash can icon), resulting in calling advertiserService.deleteAdvertiser(advertiser) with a passed argument. This possibly leads JavaScript to execute the function upon reading it immediately rather than postponing it for use after resolving the initial promise.
Could someone confirm if my reasoning behind the failure of the first code block is accurate? What is the significance of encapsulating the function within an anonymous function to correct this behavior? Is there an optimal approach to chaining these promises effectively?
Your insights are greatly appreciated!