JavaScript Promise Triggering a Function Automatically

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!

Answer №1

JS executes a function call immediately when an argument is passed in

Absolutely. By passing an argument and adding () after the function, the function is being called. Instead, you should pass a function - just like with .then(getAdvertisers) rather than .then(getAdvertisers()).

It's important to note that it doesn't have to be a function expression; you can also use .bind:

dialogService.Confirm(null, 'Delete')
    .then(advertiserService.deleteAdvertiser.bind(advertiserService, advertiser))
    .then(getAdvertisers);

which essentially does the same as

dialogService.Confirm(null, 'Delete')
    .then(function(confirmRes) {
        return advertiserService.deleteAdvertiser(advertiser);
    })
    .then(getAdvertisers);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring ways to retrieve the main project URL in ReactJS

I am currently using ReactJS and I am looking to retrieve the full path, hostname, and base URL of my project from within a component file. How can I accomplish this task? I have attempted the following code, but it is not working and is throwing the error ...

Attempting to modify/align JSON data structure

I seem to be struggling with a task that should be straightforward. I am attempting to adjust the structure and variables of a JSON object to fit specific parameters. Here is the current JSON structure I am dealing with: { "name":"BHPhotovideo", ...

Rearrange div elements following an ajax request based on a data attribute and applying the .animate method

I am dealing with a collection of div elements, each assigned a unique numeric id and data-position in sequential order (1 for the first in the list, 2 for the second, and so on). Upon making an ajax call using jQuery, the response is a JSON object that r ...

Determine the Button's State by Monitoring Changes in the TextBox Text

I have been tasked with developing a web application for my company. The main components of the application are a button and a textbox. My goal is to allow users to input a value into the textbox, which will then be processed when they click on the button ...

Opening a new window in JavaScript and passing additional parameters

I am facing an issue with my JavaScript link There is a hidden input field named "domain" Below is a div with an onclick script: <div id="button" onclick="window.open('http://www.mylink.nl/?domein=' + document.getElementById('domein&ap ...

Exploring ways to integrate Javascript and CSS into a Bootstrap lightbox modal dialog?

Can someone help me figure out how to use the bootstrap lightbox to display a form with specific CSS style and JavaScript code for the form? I'm having some trouble implementing it. I specifically need this setup because I am using Selectize.JS to cr ...

Leveraging Vue.js as a development dependency in a TypeScript project

I am currently working on a .net core project where all client-side scripts are written in TypeScript. I have a desire to incorporate Vue.js into the TypeScript codebase. Below are snippets of the necessary configurations: tsconfig.json { "compilerOpti ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Switching class on a specific element in Angular 2

My element list appears like this: <ul *ngFor="let period of periodsDate"> <li [class.show]="isShown" (click)="toggleClass()"> <a>{{ period.id }} </a> </li> </ul> ...

Experiencing a problem with the bundle.js file in Angular Universal

My Angular build is giving me this error in the web browser: Uncaught SyntaxError: expected expression, got '<' in bundle.js When I run the command npm run dev:ssr, no errors are generated. However, when I try to access the application, the ...

Retrieve the 'current' scope using a 'master' controller

I have a main controller that I refer to as my 'root' controller, which is declared using the ng-controller attribute. Additionally, I have a few other controllers that are created dynamically through a $routeProvider. I want to define a function ...

Guidelines for integrating deep links into a ReactJS Ionic Android application

I have recently converted my ReactJS project into an android project following a tutorial. Now, I have successfully created an APK file and would like to configure the app to open when a specific URL is clicked on a mobile browser. Any guidance on how to a ...

Generating innerHTML and retrieving attributes simultaneously from a single Div element

Looking for a way to extract an attribute from a div and use it to create a link within the same div with the attribute included in the src. Currently, my code only picks up the first attribute, resulting in all links being the same. I am still a beginne ...

React is throwing an error that says, "You cannot use the import statement outside a

My journey with learning React has just begun. I followed the steps outlined in the starting guide at https://react.dev/learn/add-react-to-an-existing-project, but unfortunately, I encountered an error: "Cannot use import statement outside a module." Here ...

I'm looking to leverage useEffect in React Native to effectively manage and store arrays - any tips on how

Redux has provided me with data called targetFarm, which contains an array of objects in targetFarm.children. targetFarm.children = [ {name: 'pizza'}, {name: 'burger'}, {name: 'lobster'}, {name: 'water'}, ] I am try ...

Running the JavaScript function '.hover' using Selenium WebDriver

My goal is to utilize Selenium WebDriver to run some javascript code from a webpage. I have come across several helpful posts on executing javascript, but I often struggle when trying to call javascript from page objects (I am still learning the terminolog ...

processing an array with ng-repeat taking its time

I am facing an issue with slow performance while iterating over an array of objects: $scope.items = {key1: val1, key2: val2, keyx: valx} Within my template, I am using ng-repeat in a table: <tr ng-repeat="item in items"> <td> {{item.key1 ...

The terser-webpack-plugin and uglifyjs-webpack-plugin are both powerful tools for optimizing

WebPack 4 now utilizes the terser-webpack-plugin in production mode or when the -p argument is specified, which essentially means including --optimize-minimize --define process.env.NODE_ENV="production". This plugin is responsible for minimizing ...

Instructions for triggering the opening of a colorbox within an iframe directly on top of the parent window

I am encountering an issue on a page with an iframe. When clicking on a link inside the iframe, it opens a colorbox as expected. However, the colorbox opens within the iframe itself. Is there a way to have the iframe open over the parent window instead? ...

Fixing JQuery Promise Failure in React.JS ComponentDidMount

When utilizing the ComponentDidMount life cycle method in my components, I encountered an issue with an AJAX request. Despite successfully retrieving data, the promise chain kept deferring to the fail property. This puzzling behavior persisted even when I ...