koech
koech

Reputation: 596

What is the difference between calling `done()` and calling `return` after a function completes execution?

I am confused on whether I should call done() after a function completes execution or return. I understand that calling done will mean that I have to pass it as a parameter to the function. What instances will one opt for calling return rather than done()?

i.e.

var foo = 2;
it('returns 2 on completion', function(done) {
    expect(foo).toEqual(2);
    done();
});

or

var foo = 2;
it('returns 2 on completion', function() {
    expect(foo).toEqual(2);
    return;
})

Upvotes: 0

Views: 1364

Answers (1)

alltom
alltom

Reputation: 3252

Whether you use a done() callback or simply return depends on the API you're using. A done() callback is necessary in a variety of asynchronous contexts. Off the top of my head:

In all of those contexts, the done() callback is necessary because they need to do work that can't all finish before the return. For example, tests might include random timeouts, Express middleware might make network requests, etc.

Important note: every function returns. The done() callback is a convention you use on top of that when return isn't enough because it happens too soon.

Upvotes: 1

Related Questions