What are some ways to enhance the callback pattern?

I am exploring a pattern in which function1, function2, and function3 are linked together through their callbacks.

Given that each of these functions may take up to 1 second to complete, I am interested in alternative approaches to prevent nesting from becoming unmanageable as more callback functions are added.

function1(function(cbData1){
  if(cbData1){
    function2(cbData1, function(cbData2){
      if(cbData2){
        function3(cbData2, function(cbData3){
          // success
        }
      } else {
        // failed for reason#2
      }
    });
  } else {
    //failed for reason#1
  }
});


//example function
function function2(data, callback) {
  // carry out necessary operations
  callback(newData);
}

Answer №1

It seems like you're looking to structure the callbacks in a sequential manner. Have you considered implementing the Chain of Responsibility pattern?

You can achieve this by creating an object that holds both the main function to execute and any callback functions that may be required.

Answer №2

Once, when dealing with tricky callbacks, I found a solution that looked something like this:

// Quickly put together
var callbackList = [];  // Array to store callback functions.

function doNextCallback() {
  if (callbackList.length) {
    var f = callbackList.shift(); // Get the next function from the list
    window.setTimeout(f);         // Add delay for readability.
  }
}

// Setting up the callbacks
callbackList.push(callback1);
callbackList.push(callback2);
callbackList.push(callback3);

// Start executing callbacks.
doNextCallback();          

function callback1() {
  console.log("Performing task A");
  doNextCallback();
}

function callback2() {
  console.log("Performing task B");
  doNextCallback();
}

function callback3() {
  console.log("Performing task C");
  doNextCallback();
}

I had organized everything neatly in an object, but you can understand the concept.

This approach also allowed easy rearrangement of callbacks or running only specific ones repeatedly for testing purposes.

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

Pinterest-style Angular-UI-Router modal

I am currently working on an app that features a gallery showcasing similar functionalities to . In Pinterest, clicking on a pin displays the pin page above the existing gallery without any information about the background gallery shown in the URL. Users c ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

Difficulty arises when attempting to create JSON using the Array.push() function from the data received via Ajax. The generated JSON is not successfully populating the tbody element

I am facing an issue while populating my tbody with data using the code below: function adaptSelectedBanks(banks) { console.log(banks.length); $(function() { banks.forEach(function (ba) { var c ...

Upon attempting to open Google Maps for the second time, an error message pops up indicating that the Google Maps JavaScript API has been included multiple times on this page

Currently, I am utilizing the npm package known as google-maps and integrating it with an angular material modal to display a map. However, upon opening the map for the second time, an error message is triggered: You have included the Google Maps JavaScri ...

Creating a dynamically generated JavaScript array using the JSON format

I am in need of creating an array of JSON data. Here is an example: [ { "DataCategoryGroupId": "22222222-2222-2222-2222-222222222222", "AnswerOptionIds": [ "76e32546-0e26-4037-b253-823b21f6eefb", "10d02a3e-9f9f- ...

Should the page.js in a Next.js App router be a server component?

Is it standard practice in Next.js 13 and above (App router) for the page.js of all routes/folders to be a server component? I know that it can be a client component with use client, but is this advisable or are there potential issues during the build proc ...

Send the values of a textbox using an AJAX request in PHP whenever the textbox is changed or loses focus

I'm having trouble with my autocomplete address Google API textbox in my form. Whenever I select an address, I need to retrieve the latitude and longitude of that address and pass those values in my AJAX request. However, I keep getting null values ev ...

What could be causing this error to occur when running my React app and clicking the submit button on the form?

CodeBlock.js import React from "react"; import { useState } from "react"; import axios from 'axios' const CodeBlock=()=>{ const [formData, setFormData]=useState({name:'', password:''}); const hand ...

Create a canvas that extends the width and height of its parent container

Looking to create a rectangular canvas that acts as a progress bar, but struggling with setting the width and height to 100%. It doesn't seem to fill the parent container properly. Check out this example below: http://jsfiddle.net/PQS3A/ Is it fea ...

How to capture the "chip close" event in Vuetify

Exploring the vuetify realm as a newcomer, I find myself grappling with event handling while working on my first web app project. Specifically, I am currently developing a "UserPicker" component using VAutocomplete. This component functions by sending an ...

Retrieve data visualization tools from a separate function

Below is a Google dashboard featuring filtering, sorting, and paging functionality. I need to programmatically modify the sourceData and refresh the Google visualization from outside its containing function. The challenge is accessing the visualization fr ...

Approval still pending, awaiting response

Encountering an issue with a POST request using React and Express, where the request gets stuck in the middleware. I am utilizing CRA for the front end and Express JS for the backend. Seeking advice on troubleshooting this problem. Backend server.js var ...

What is the best way to ensure one asynchronous function has completed before executing another function in Swift?

Currently, I am facing an issue with a function that needs to complete running all its code before moving on to another function. My dilemma is that this function is asynchronous, so it skips ahead to the next function without finishing all the necessary ...

Insert a point onto the SVG polygon along the nearest line to the click event

In my React app, there's an SVG polygon element that initially appears as a square but can have new points added by double clicking inside the polygon area. I'm trying to ensure that the point is added to the side of the polygon closest to the p ...

Unravel the ReadableStream object in nextjs 13 api route

I am encountering an issue with my server-side code where a value I am sending is not being interpreted correctly. My project is utilizing the experimental App directory feature of NextJS. //src/app/api/auth/route.js export async function POST(req, res) { ...

Is it possible to optimize the Dojo build system to only compile Dojo when necessary?

Greetings. I've been assigned the challenging task of enhancing the efficiency of the Javascript build process in our application. The current setup involves using Dojo libraries and build system, which takes approximately 6 minutes for a complete bui ...

To make sure that async tests and hooks are properly handled, remember to call "done()" after completion. If you are returning a Promise, make sure that it resolves properly for puppeteer and

I am currently testing my component using mocha and Google Puppeteer. In my unit test file, I have set up the Puppeteer browser to launch before the tests and close after the tests in the respective functions. However, when running the test file, I encou ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

Passing events from one controller to another in AngularJS using methods such as $broadcast and $window.localStorage

Looking to dispatch an event to another controller, I am familiar with techniques involving $rootScope.$broadcast, $scope.$emit, and then listening for the event using $scope.$on. This is a common approach, but in my project, controllers are initialized i ...

Testing AG Grid's TypeScript in-line cell editing using Jest

I am currently working on writing Jest tests to evaluate the functionality of my ag-grid table. So far, I have created tests to check the default data in the grid and to test a button that adds an additional row of data to the grid. I am now attempting t ...