Is your Node.js asynchronous parallel function not performing as expected?

I have a series of promises that I need to execute sequentially, but it's getting messy with all the promise returns. To simplify this process, I decided to use the async library and tried out the parallel method. However, instead of running one after the other, my promises were running independently as they should.

Interestingly, all the console.logs were appearing before the promises had finished executing.

async.parallel([
        (cb) => {
          console.log ("hi")
            grabMeData(Args)
              .then((data) => {

                // Promise completed, moving on to the next function
                cb();
              }).catch(()=>console.log('err'));
        },
        (callback) => {
          // Previous promise done, I'm the callback
          Query.checkUserExists()
          .then(() => {
            if(Query.error) {
              console.log(Query.error); // Handle error
              return; // Return to client if necessary
            }
            callback();
          });
        },
        () => {
          // Previous promise resolved, I'm the callback

          // Originally asynchronous 
          if (Query.accAlreadyCreated) {
            this.NewUserModel.user_id = Query.user_id;
            this.generateToken();
          } else {
            console.log("account not created");
          }
          console.log('xx')
        }
    ], () =>{
      console.log("Finished executing async parallel")
    });

Do you know why my callbacks are running before the promises are resolved (.then)?

Answer №1

In agreement with Bergi, using async.js becomes unnecessary when utilizing promises. Your code can be streamlined as follows:


console.log('hello')
fetchData(Arguments)
  .catch(error => console.error(error))
  .then(() => Query.verifyUser())
  .then(() => {
    if (Query.accountCreated) {
      this.UserModel.userId = Query.userId
      return this.createToken()
    } 
    console.log("account not yet created")   
  })
  .then(() => console.log ('xy') )

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

When attempting to use AngularJS to post to Express 4, the return is a bad request

I've encountered an issue with posting AngularJS to Express 4.0 and could use some help! After taking a MEAN stack course on Pluralsight, I downloaded the source code from my instructor's GitHub repository (Github - Course Source Code). You can ...

Encountered a Node Express Post 500 error (Internal Server Error) triggered by jquery-3.4.1.min.js

Recently, I've been immersed in developing a node js/express js application for quite some time. Most of my get's and post's are functioning properly when triggered from jquery $ajax calls. However, there seems to be an issue with one speci ...

Whenever I click on a button, I want to modify the background color of my react-modal

Having an array of images with clickable overlays and a modal that changes the background color based on the overlay name when clicked is the goal. However, passing this value as a prop proves challenging since the images are generated through a function a ...

NPM encountered an issue while attempting to perform the installation

Having some issues with NPM while trying to install various apps. The errors that I am encountering are outlined below: npm ERR! Darwin 14.5.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "ember-cli" npm ERR! node v4.0.0 npm ...

Guiding motion of a parental container using a button

This seems like a fairly straightforward task, but I'm getting a bit frustrated with it. Is there a way to move an entire div by simply holding down the mouse button on a particular button? let container = document.getElementById('abo ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...

jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cl ...

What is the importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

What is the best way to transform these nested callback-heavy functions into async await or promises?

I'm relatively new to Node.js and I need to execute a series of functions one after the other, as they are interdependent. Initially, I opted for the callback function approach where I invoked another callback, essentially creating nested callbacks in ...

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

Module not found

Hey everyone, I recently updated my project to node version v14.18.0, but now I'm encountering a "module not found" issue (see screenshot below). Any suggestions on how to resolve this? https://i.stack.imgur.com/k0u82.png ...

The NEXT13 App Router encountered an issue: ReferenceError - the navigator object is not defined

I am in the process of developing a video chat application and I have encountered an issue while working on it (no problems when running npm run dev). Please excuse the messy code for now, I promise to clean it up once I resolve this problem: Here is the ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

Using the Angular translate filter within a ternary operator

I am currently working on translating my project into a different language. To do this, I have implemented the Angular Translate library and uploaded an external JSON file containing all the translations. Here is an example of how it looks: { "hello_wor ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

The command 'npm-run-all' is not valid and cannot be found, please check the command and try again

#Issue : Error running npm run dist for Bootstrap #Error Detail: 'npm-run-all' is not recognized as a valid command, program or batch file. Recently installed Node.js and chocolatey. Verified everything added to the system path. Attempting to ex ...

The jQuery date picker refuses to function correctly when I attempt to initialize it after an AJAX call

I am facing an issue with my jquery-ui datepicker not working within the document.ready function after making an ajax call. However, it works fine when I add it inside the ajax complete function. Can someone please provide assistance on what could be cau ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...