Home Do something after multiple async mongoose calls finishes
Reply: 0

Do something after multiple async mongoose calls finishes

user9563 Published in September 21, 2018, 8:05 am

I have a function that looks up data in several different documents, add some of the date from each document to a object and returns the object with the combines data from the different documents. The only problem is that the object is returned before any of the transactions are completed. I have googled a lot, and the only solution i can find is on Stack Overflow, but from 2012.... There must be some "newer" better way to do it? Preferably without installing more npm stuff.

Here is my function

function getPreviousEventCard(event, callback) {
    const card = {};
    card.dateStart = event.dateStart;
    card.dateEnd = event.dateEnd;
    card.userID = event.userID;
    card.adminID = event.adminID;

    // 1st async call
    Profile.getFullName(event.userID, (err, name) => {
        if (err) return callback(err, null);
        card.bsName = name.fullName;

    // 2nd async call
    Profile.getProfileByUserId(event.parentID, (err, profile) => {
        if (err) return callback(err, null);
        card.parentName = profile.fullName;
        card.address = `${profile.address} ${profile.zip}`

    // somehow wait until both(all) async calls are done and then:
    return callback(null, card);

btw, 'Profile' is a mongoose schema, and the get methods are using the findOne() method.

I have tried to nest the functions and have the return callback as the most inner, but then it is never returned for some reason.

share|improve this question
  • What version of Node are you using? – T.J. Crowder Feb 13 at 15:07
  • Do Profile.getFullName return a Promise? If yes you should definitely use async await – Naramsim Feb 13 at 15:08
  • What stuff on SO did you find and why do you think it isn't good enough? Have you looked into Promise.all()? I would expect getFullName() and getProfileByUserId() to return Promises. – zero298 Feb 13 at 15:08
  • Put your 2nd async call inside the callback of the 1st async call. Then the 2nd async will not run until the 1st is complete. – Jeff Matthews Feb 13 at 15:08
  • Jeff, I dont think thats a good idea, then i will wait before starting the other aync call... it would be most efficient to start them at the same time since the DB is independent of the CPU where the calls are made. @zero298 cant find it again... but it seemed outdated to me. – Rasmus Puls Feb 13 at 15:15

1 Answer 1

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.398682 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO