James111 James111 - 6 months ago 22
Node.js Question

Node.js async parallel not working how it should be?

I've got multiple

promise
' that I want to run one after the other, and I'm not sure I want to be returning the promises as it gets pretty messy!

So I decided to use the
async
library and implement the
parallel
method. Now I noticed that all my promises weren't running one, after the other, instead they were doing what promises are suppose todo (run + finish whenever).

I noticed that all the console.logs were running before all the promises were finished.

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

// The promise is done and now I want to goto the next functio
cb();
}).catch(()=>console.log('err'));
},
(callback) => {
// The above promise is done, and I'm the callback
Query.checkUserExists()
.then ( () => {
if (Query.error) {
console.log (Query.error); // Determine error here
return; // Return to client if needed
}
callback();
});
},
() => {
// The above promise is done and I'm the callback!

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


Any reason why my callbacks are being run
before
the promises are resolved (.then).

Answer

like Bergi said, async.js is redundant when you use promise, your code can be simplified as:

console.log('hi')
grabMeData(Args)
  .catch(e => console.error(e))
  .then(() => Query.checkUserExists())
  .then(() => {
    if (Query.accAlreadyCreated) {
      this.NewUserModel.user_id = Query.user_id
      return this.generateToken()
    } 
    console.log ("account not created")   
  })
  .then(() => console.log ('xx')  )
Comments