Executing functions in AJAX using JavaScript callbacks

I'm in need of assistance to grasp how to start working on this problem.

I have a task to write code for an object that allows multiple functions to be registered to execute a single common callback function.

The objective of the object is to run all the registered functions, and once they are all completed, it should trigger the defined callback function.

For instance, if I invoke MyFuncs.start(), the MyFuncs object would begin executing all the registered functions asynchronously. After the last one finishes, only then will it execute the callback function.

Could someone please direct me to online resources or provide guidance on how to get started with this issue?

I've written some code to achieve this, but I seem to be facing difficulties in getting the desired outcome. Can anyone assist me with this and also let me know whether my approach is correct or not?

Here's my code:

var MyNewClass=(function()
{
    return function()
    {
        this.registeredFunctions=2;
        this.count=0;
        this.function1=function()
        {
            $.ajax(
            {
                url: '/echo/html/',
                success: function(data) 
                {
                    alert('request complete');
                    this.markDone();
                }
            })
        };

        this.function2=function()
        {
            $.ajax(
            {
                url: '/echo/html/',
                success: function(data) 
                {
                    alert('request complete');
                    this.markDone();
                }
            })

        };

        this.register=function(newFunction)
        {
            this['function'+(++registeredFunctions)]=newFunction;

        };

        this.start=function()
        {
            this.function1();
            this.function2();
        };

        this.callback=function()
        {
            alert("I am callback");
        };

        this.markDone=function()
        {
            this.count++;
            if(this.count==this.registeredFunctions)
            {
                alert("all function executed,calling callback now");
                callback();
            }

        };
    };

})();
$(document).ready(function()
{
    $('.start').click(function(){
        var o=new MyNewClass();
        o.start();
    });
});

Note: I cannot use $.when from jQuery because the user may send any function to register, and it's not guaranteed that those defined functions will return me a deferred object.

This is why I cannot utilize $.when in this scenario.

Alright, I've found the solution and I'll share it here so it can benefit others as well.

The solution is provided below.

Answer №1

In this JavaScript file, I have defined my class along with all the functions.

var MyCustomClass=(function()
{
    return function()
    {
        this.registeredFunctions=0;
        this.count=0;
        this.register=function(newFunction)
        {
            this['func'+(++this.registeredFunctions)]=newFunction;

        };

        this.begin=function()
        {
            for(var i=1;i<=this.registeredFunctions;i++)
                this['func'+i]();
        };

        this.handler=function()
        {
            alert("This is a callback");
        };

        this.completeTask=function()
        {
            this.count++;
            if(this.count==this.registeredFunctions)
            {
                alert("All functions executed, calling the callback now");
                this.handler();
            }

        };
    };

})();

Another JavaScript file where users can register functions.

$(document).ready(function()
{
    $('.start').click(function(){
        var obj=new MyCustomClass();
        function b()
        {
            $.ajax(
            {
                url: '/echo/html/',
                success: function(data) 
                {
                    alert('New task complete');
                    obj.completeTask();
                }
            })

        };
        obj.register(b);
        obj.begin();
    });
});

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

The error "ReferenceError: Component is not defined in Meteor" indicates that the Component

I'm facing an issue while trying to display my Deal component and encountering the error mentioned below. I am currently utilizing Meteor along with ReactJS. Uncaught ReferenceError: Deal is not defined at meteorInstall.imports.routes.routes ...

What is the best way to immediately update the state in a React functional component?

Having recently started learning React, I find myself struggling to understand the lifecycle of a functional component. Let's consider a scenario where I have multiple checkboxes labeled as: checkbox, a, b, c, and d, each corresponding to values a, b, ...

Having trouble positioning the right side image on the Bootstrap 4 Landing page

Struggling to incorporate bootstrap 4 into my sample project for the right side background. I'm facing some conflicts and attempts to align it on the right side are not successful. Does anyone know how to do this correctly? Thank you // Navbar scr ...

The issue with Grid component in Nested Single file Component

I'm currently working on creating a grid component in Vue to set up a sortable and searchable chart using Single File Component. I've also integrated vue-router into the project. Below are my two .vue files. At the moment, I can only see the sear ...

Implementing Twitter Login with Vue, Vuex, and Firebase

Exploring a Twitter login option for my sports social media dashboard project, I followed a helpful tutorial. While I've successfully implemented the HelloWorld component and retained the app.vue and main.js components, I encountered an error stating ...

Create a new array containing the keys from an array of objects

My task involves extracting the key puppies from an array of objects and returning it in a new array: The input is an array of dogs structured like this: [ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof&ap ...

Is there a way for me to modify the color of the currently selected button?

I've been attempting to change the color of the active button when clicked, but my CSS class "activePage" isn't doing the trick. Ideally, clicking the "projects" button should turn it red, and clicking the "about" button should change it to red w ...

What could be causing my form not to Submit when attempting submission without utilizing the submit button?

Here is the code for my validation: $(function () { function validateForm() { // Code to validate form inputs } $('#myform').submit(validateForm); }); After this, I want to submit the form when a certain action occurs: < ...

Ember Data's counting model feature

After searching through numerous examples on Stackoverflow, I am still struggling to grasp the concept of how get('length') functions. I am attempting to retrieve a user count in the helper model. The issue may lie in my approach to using get(&a ...

Tips for creating text that changes size based on the container dimensions

I am looking for a way to ensure that the content within a div container remains neatly contained without overflowing. How can I make the container responsive so that it adjusts its size based on dynamic text? .element { display: inline- ...

Clicking the button will close the active tab in Firefox

I need help with a webpage that has a popup. When the user clicks the OK button in the popup, I want the current tab to close. The OK button is an HTML input tag. I've tried various ways of using JavaScript's close method and searched online, but ...

Guide for setting up a React infinite scroll feature in a messaging app similar to Facebook Messenger

I have been exploring various questions regarding React infinite scroll, but I am looking to delve deeper in order to discover the most effective solution available for implementing such a component. Currently, I am working on a chat application and have ...

What is the best way to display an overlay internal link on top of the current one after it has been clicked

I am looking to create a button that, when clicked, will slide in a different page link and modify the URL to cover 80% of the website, while keeping the previous page in the background. Upon closing, the URL will revert back to the original one. I have c ...

In order to properly set up an AutoNumeric object, it is essential to have at least one valid parameter provided

I've been working with the AutoNumeric library in my Vue js V2 application and keep encountering a specific error message in the console Issue with mounted hook: "Error: At least one valid parameter is needed to initialize an AutoNumeric object& ...

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

Are elements such as String and Number to be classified as "constructor functions" within JavaScript programming?

After spending a few weeks poring over tutorials, I've finally uncovered an interesting fact. When using the prototype property on a constructor function, the key/value pairs on that prototype property are actually copied to the proto property of the ...

"Discover the steps to seamlessly integrating Snappuzzle with jQuery on your

I am a beginner when it comes to javascript and jquery, and I recently came across the snappuzzle plugin which caught my interest. After visiting snappuzzle plugin, I decided to download and link jQuery, jQuery UI, and the snappuzle.js in my HTML file. I a ...

Using jQuery to open a file containing an umlaut in its filename

I am trying to retrieve the content from a file that contains an umlaut in its filename using a jquery load request. I understand that it is not recommended to use umlauts in filenames. What's puzzling is that I have used the same code, with the same ...

Guide on adjusting shipping costs in Stripe based on the customer's address using NodeJS

Utilizing Stripe's Checkout API, I am seeking to provide international shipping options with varying costs based on the country selected at checkout. Is there a method within Checkout that allows me to dynamically adjust shipping costs based on the us ...

Update specific records seamlessly on my website without requiring the entire page to refresh

Is there a way to update a record without refreshing the page? I have a system where I need to toggle a feature on or off by changing its status between 0 and 1. Here is the form that allows me to do this: <table class="tablesorter" cellspacing="0"> ...