What is the best way to handle resolving a Q deferred object multiple times in a step-by-step manner?

In my sequence of functions, the first function is asynchronous and returns a promise. This first function also calls other async functions. The second function should only be called when all the nested functions have completed. Therefore, I need to resolve the deferred object at multiple points within the chain (in this example, within three nested functions).

var deferred = Q.defer();
first().then(second);

function first() {
    nestedAssyncFunction_1();
    nestedAssyncFunction_2();
    nestedAssyncFunction_3();
    return deferred.promise;
}
function second() {
    // perform some actions
}

My primary question here is: how can I resolve a deferred object in multiple steps?

I have discovered that by using the `notify` method at various points and resolving the main deferred object inside its handler seems to work. Here is an example:

var deferred = Q.defer();
deferred.progressCounter = 0;

first().then(second, undefined, notifyHandler);

function notifyHandler() {
    deferred.progressCounter++;
    if (deferred.progressCounter === 3) {
        deferred.resolve();
    }
}
function nestedAssyncFunction_1() {
    // perform some actions
    deferred.notify();
}

However, this brings me to another question: what is the most effective way to add custom properties to a deferred object? It appears to be discouraged based on the example above.

Thank you.

Answer №1

That is definitely not the desired outcome.

The preferred solution is as follows:

Q.all([
   executeNestedAsyncFunction_1(),
   executeNestedAsyncFunction_2(),
   executeNestedAsyncFunction_3()
]).then(function(){
    //Tasks completed successfully
});

Answer №2

One way to approach this is as follows:

function start() {
    // Each nested function must return a promise
    var promises = [];
    promises.push(nestedAsyncFunction_1());
    promises.push(nestedAsyncFunction_2());
    promises.push(nestedAsyncFunction_3());

    var deferred = Q.defer();
    Q.all(promises).then(function(){
         // Perform tasks after all promises are resolved.

         deferred.resolve(); // Resolve the deferred object when all promises are resolved.
    });
    return deferred.promise;
}

function continueAction() {
    // Carry out some actions
}

Alternatively, consider this solution based on your specific requirements:

function start() {
        // Each nested function must return a promise
        var promises = [];
        promises.push(nestedAsyncFunction_1());
        promises.push(nestedAsyncFunction_2());
        promises.push(nestedAsyncFunction_3());

        var deferred = Q.defer();
        promises.push(deferred.promise); // Add the promise of the current function

        // Implement asynchronous operations within the current function and call deferred.resolve()

        return Q.all(promises); // Combine all promises into one
    }

    function continueAction() {
        // Carry out some actions
    }

Execute the functions in sequence like so:

start().then(continueAction);

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

Troubleshooting: Why isn't my Angular directive being updated by the controller?

My directive is responsible for displaying a detail screen when a row is clicked. I am currently working on updating the encounter within this directive. Take a look at the code below: angular.module('app').directive('chatContainer', f ...

The behavior of relative paths in Ajax can vary depending on the environment in which it

This website is built using SpringBoot. The URL for the HTML page is . Here is a segment of JavaScript code found on the index page: $(function(){ jQuery.ajax({ contentType:'application/json;charset=UTF-8', type: "POST", url: "getSi ...

After 20 seconds, the Ajax request returns an 'error'

Attempting to make a server call results in the response containing data from a database query. However, this query takes a long time (50s). The ajax request finishes on the error function 20s after it was initiated by the client: $.ajax({ type : ...

Issue with Showing Hidden Section using Jquery - Try it Out on JSfiddle!

I'm struggling with a script that should reveal a hidden <div> when a checkbox is clicked. Despite my best efforts, I can't seem to get the section to display correctly. The snippet of code in question looks like this... If you'd like ...

Strategies for resolving the module not found error: Unable to locate '@mui/icons-material/Adb'?

I installed material-ui core using the command below: npm i @material-ui/core However, when running my reactjs code afterwards, I encountered this error message: Module not found: Can't resolve '@mui/icons-material/Adb' Can someone pleas ...

The presence of asynchronous JavaScript can lead to errors due to missing functions in JavaScript

I've encountered an issue with a jQuery script that I modified by adding an ASYNC attribute. Surprisingly, it functions correctly in Firefox but encounters intermittent failures in both Chrome and IE browsers. Here's the PHP code snippet respons ...

What is the best way to receive a single response for various API endpoints?

I need to retrieve a single response from an API that has multiple page URLs. How can I accomplish this with just one API call? Here is my code: async function fetchArray () { // Fetch `urlArray` from object parameter let urlArray = []; ...

Is there a way to execute a function for every element of an array using a for loop in Javascript?

I have been working on a script to calculate the sum of inputted numbers, including integers and "-" symbols. However, I am facing an issue where the code only calculates the sum for the first number in the array and then returns undefined. I understand th ...

Utilizing X-editable and Parsley to trigger dual Ajax calls

Here is a snippet of code I am working with: $.fn.editable.defaults.mode = 'inline'; var editable = $('.x-editable').editable({ send: 'always', validate: function() { var form = editable.next().find('form ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

Error: The React styleguidist encountered a ReferenceError due to the absence of the defined

After integrating react styleguidist into my project, I encountered an issue when running npm run styleguidist. The error message states: ReferenceError: process is not defined Here is a snippet from my styleguide.config.js file: module.exports = { ti ...

Extract the value from an input-select in VueJS instead of the key

Here is the input-select code snippet: <input-select v-model="county" id="county" :options="getCountyList()"> &dagger; County </input-select> The function getCountyList() is defined as follows: getCountyList ...

Guide to building a multi-dimensional array from a flat object

My endpoint is outputting data in a specific format: const result = [ {id: 4, parentId: null, name: 'Fruits & Veggies'}, {id: 12, parentId: 133, name: 'Sanguinello'}, {id: 3, parentId: 4, name: 'Fruits'}, {id: 67, ...

Verifying the status following a promise execution in the initial promise function

Below is the function I am currently working with: startGame = () => { this.buildDeck() .then(this.shuffleDeck) .then(this.dealToPlayer) .then(setTimeout(this.dealToPlayer, 2000)) .then(setTimeout(this.dealToDealer, 4000)) } In ...

retrieve a changing identifier from a nested iframe within another iframe

There's a challenging task at hand - creating a pack of resources (website pages) through the use of iframes to display page content. The tricky part arises when dealing with multiple iframes within one iframe. The objective is to pass specific style ...

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

Issue with Google Tag Manager click event not propagating to parent element

I am currently configuring Google Tag Manager for a client's website and encountering difficulties in getting click event tags to activate. Although I have set the trigger to activate based on the button's CSS selector, the actual button contain ...

Issue: the size of the requested entity is too large

Encountering an error message while using express: Error: request entity too large at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15) at json (/Users/ ...

Guide on refreshing a div's content following an AJAX request

I have a container (<div class="card-body">) and I want to insert elements from the database dynamically (using AJAX) However, I require a dynamic solution as I will be adding content on-the-fly and Django template tags alone are not suffi ...