create a callback method for an asynchronous operation

After some research, I came across a helpful callback function that can pause the execution of a script until another script is finished. The solution was found here.

dosomething(4, function () {
    console.log("finished loop");
});


function dosomething(delay, callback) {

    for (var i = 0; i < 100; i++) {
        $("body").append(i + "<br>");
    }
    alert("done");
    if (typeof callback == "function") callback();

}

FIDDLE

It's worth noting that this method won't work with asynchronous functions, as I discovered.

doAjax(4, function () {
    console.log("finished ajax");
});

function doAjax(delay, callback) {
    $.ajax({
        type: "post",
        url: "/echo/html/",
        data: {
            html: "some content",
            delay: 4
        },
        dataType: 'html',
        success: function () {
            console.log("ajax done");
        }
    });

    if (typeof callback == "function") callback();
}

FIDDLE

While it may seem unnecessary to create custom callbacks for asynchronous requests when jQuery provides built-in functionality, I was curious about how it could be accomplished. Is it as involved as developing an entire promise library?

Answer №1

Make sure to trigger your callback function once the request is complete.


...
//CALLBACK NEEDED HERE!
success: function(data){
  if (typeof callback == "function") callback(null, data);
},
error: callback
...
//DO NOT PLACE BELOW THIS LINE

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 the archive of content with AJAX back button tracking

Greetings, Before considering this question as a duplicate, I would like to mention that I have thoroughly searched for similar questions but none of them address my specific issue. Below is a simple example, and any assistance you can provide would be hig ...

AngularJS restricts inputs to be read-only

I'm facing an issue with readonly inputs in AngularJS. I have a select element that changes the values of readonly inputs through a script. However, when I attempt to display these values using ng-model in a table as {{ng-model}}, they don't appe ...

Generate a document from the data entered in an HTML form using the web browser (on the client side)

My website contains a form and I want users to be able to generate a text or xml file based on their input. However, I prefer not to set up a web server just for this purpose. Is there a feasible solution for achieving this, possibly with the use of Javas ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

What is the best way to implement the hasMany relationship functionality with the Kysilk column-sortable package?

Can anyone explain how to implement the hasMany relationship using kysilk column-sortable package? public function renterCount() { return $this->hasMany('App\RentalApplication','property_id', 'id'); } ...

Issues that could arise with a chat app

I am in the process of developing a website that will feature both personal and group chat capabilities, similar to those found on platforms like Facebook. Before I begin coding, I have a few questions that I would like to address. My current plan is to b ...

Eslint was unexpectedly unable to detect any errors in the .ts files

After creating a SvelteKit project with npm create svelte@latest, I included some .ts files for a particular library. However, when running eslint ., it fails to detect any errors. The default eslint config generated from Svelte is as follows: .eslintrc. ...

Utilize a Fancybox hyperlink for every image within the specified div container

I'm looking for a solution to automatically add a fancybox link to every image within the div #artikel. Essentially, I want to convert each <img src="image.png"></img> to <a href="image.png" class="fancybox" rel="artikel"><img ...

``I am experiencing issues with the Ajax Loader Gif not functioning properly in both IE

I am brand new to using ajax and attempting to display a loading gif while my page loads. Interestingly, it works perfectly in Firefox, but I cannot get it to show up in Chrome or IE. I have a feeling that I am missing something simple. The code I am using ...

What steps can I take to address the issue of missing modules in an Angular application?

I am facing an issue with my Angular application where I am using two local libraries. Despite having all dependencies declared and imported correctly, the build process continues to throw errors related to missing modules. To give you a better picture of ...

Using AJAX callback in PHP as a class method with a defined namespace

Every time I attempt to use a class method for an ajax callback, I encounter a server error. I suspect that PHP namespaces (particularly for a composer autoloader) may be the culprit. This suspicion was confirmed when I replaced use with require and the co ...

What is the best way to combine key-value pairs objects into a single object using JavaScript?

I am faced with the challenge of creating a new object that combines keys from a specific array (const props = []) and values from existing objects. If a key does not exist in an object, I aim to populate it with null or placeholder values. Here is my cur ...

Emphasize the active page in the main menu

I'm struggling to use JavaScript and jQuery to highlight the current list item on my main menu. As a beginner in scripting, I am having trouble figuring out what's wrong with the code. Here is the code snippet that I have been working with. < ...

Exploring ways to incorporate whitespace and newline characters in the split function

Looking for assistance with iterating through a string that contains multiple words separated by spaces and new lines (\n). Here's an example: message: dob cat dog dog cat cat I tried using the following function to split the mes ...

Solving Timezone Problems in DayJS React and MongoDB_integration

Whenever I save a record to MongoDB, I include the created date using Date.now as shown below: createdAt: { type: Date, default: Date.now } After saving it in MongoDB, the record appears like this: createdAt: 2023-02-01T01:39:03.377 ...

Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here. This is the code snippet from my A ...

What is the significance of using the variable name "$scope" in coding?

As a newcomer to Javascript, I recently finished reading the book Eloquent Javascript and am now delving into AngularJS from O'Reilly. While working on a code snippet provided in the AngularJS book, I encountered hours of frustration trying to figure ...

JavaScript function implemented to add query parameters to HTTP requests

While reviewing my Google Analytics data, I noticed some recurring requests with a script in the query parameter. The format looks something like this: /about?RaNDMPRMz='-function(){debugger}()-">\"><scrIpt>debugger</scrIpt>< ...

How can I specify the file path for an image or any other file in a .js or CSS file within DotnetNuke?

Currently, I am delving into DotnetNuke 7 and am in the process of developing a Module using ASP.Net. After successfully creating the Module in Visual Studio 2015, I uploaded it as an Extension in DotnetNuke at www.dnndev.me. All aspects of the Module are ...

Ajax: What could be causing the post request to be triggered twice?

I am puzzled by the fact that my request is being sent twice, without any clear reason. Here is the code for my simple form: <form method="POST" class="mb-4" autocomplete="off" action="/recipe/add" novalidate id="form"> <div class="form-grou ...