HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Am I using Q the right way or is there a better way to do what I'm doing?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thewhatwaydoingbetterusingthereright

Problem

I'm using Q to flatten out some callbacks in my unit tests and return a promise to mocha (which knows to wait until the promise is resolved before running the next test).

Originally I had this code:

it ('resetCount should cause the count to reset as if there were no documents yet.', function () {
    // Now save user and check if its _id is what nextCount said.
    user.save(function (err) {
        should.not.exists(err);
        user._id.should.eql(0);

        // Call nextCount to check the next number. Should be one.
        user.nextCount(function (err, count) {
            should.not.exists(err);
            count.should.eql(1);

            // Now reset the count.
            user.resetCount(function () {
                // Call nextCount again to check that the next count is reset. Should be zero.
                user.nextCount(function (err, count) {
                    should.not.exists(err);
                    count.should.eql(0);
                    done();
                });
            });
        });
    });
});


With Q I turned it into this:

```
it('resetCount should cause the count to reset as if there were no documents yet.', function () {
var userSchema = new mongoose.Schema({
name: String,
dept: String
});
userSchema.plugin(autoIncrement.plugin, 'User');
var User = db.model('User', userSchema);

// Create user and save it.
var user = new User({name: 'Charlie', dept: 'Support'});
// Now save user and check if its _id is what nextCount said.
q.nmcall(user, 'save')
.then(function (user) {
user._id.should.eql(0);
return q.nmcall(user, 'nextCount');
})
.then(function (count) {
count.should.eql(1);
return q.nmcall(user, 'resetCount');
})
.then(q.nmcall(user, 'nextCount'))
.then(function (count) {
count.should.eql(0);
}, function (err) {
should.not.exists(err);

Solution

.then(q.nmcall(user, 'nextCount'))


is wrong. The nextCount call does return a promise (and starts its execution right away), while then does expect a [callback] function. You'd rewrite it to

.then(function(result_of_resetcount) {
    return q.nmcall(user, 'nextCount');
})


or shorten it with nfbind/nbind:

.then(q.nbind(user.nextCount, user))

Code Snippets

.then(q.nmcall(user, 'nextCount'))
.then(function(result_of_resetcount) {
    return q.nmcall(user, 'nextCount');
})
.then(q.nbind(user.nextCount, user))

Context

StackExchange Code Review Q#34062, answer score: 3

Revisions (0)

No revisions yet.