terpak
terpak

Reputation: 1151

NodeJS: Returning data from an async function

I'm trying to write a function to create a new user on my database (mongodb) and then return that user as an object which I defined. However, since the call to insert the user is async, result.nInserted is always undefined because the async code doesn't finish in time. Therefore, I never get to return my user. I would try and use callbacks to fetch the user after it is done being inserted, but then how would I be able to return that data from my original addUser function?

User.addUser = function(db, email, username, password, firstname, lastname, company, twitter){
    var _id = new mongodb.ObjectID();

    var result = db.get('users').insert({
        _id: _id,
        email : email,
        verified : false,
        password : password,
        username : username,
        firstname : firstname,
        lastname : lastname,
        company : company,
        twitter : twitter,
        rank : config.RANK_USER
    });

    return result.nInserted == 1 ? new User(_id, email, false, username, firstname, lastname, company, twitter, config.RANK_USER) : false;
};

Upvotes: 1

Views: 241

Answers (2)

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3645

From documentation:

Insert

Records can be inserted to a collection with insert

collection.insert(docs[[, options], callback])

So what you want can be done via callback function.

I think you can solve your task

User.addUser = function(db, email, username, password, firstname, lastname, company, twitter, callback){
var _id = new mongodb.ObjectID();

db.get('users').insert({
    _id: _id,
    email : email,
    verified : false,
    password : password,
    username : username,
    firstname : firstname,
    lastname : lastname,
    company : company,
    twitter : twitter,
    rank : config.RANK_USER
}, callback);
};

So callback function will be called when insertion is completed.

It receive two arguments: error and result.

function callback(err, res){
  // some actions
}

Read this question, it can help!

Upvotes: 2

Michal Lison
Michal Lison

Reputation: 489

You have to use a promise pattern here:

return result.then(function( myNewUser ){
   return new User(myNewUser._id, email, false, username, firstname, lastname, company, twitter, config.RANK_USER);
})

Upvotes: 0

Related Questions