Reputation: 23737
Given this code:
c = new Customer
c.entry phone,req #how to make sure it ends before the next piece of code?
db.Entry.findOne {x: req.body.x}, (err,entry) ->
How do I make sure that db.Entry.findOne is only executed after c.entry completes?
class Customer
entry: (phone,req) ->
Upvotes: 2
Views: 160
Reputation: 434615
Presumably your entry
method does something asynchronous and that something should have a callback that runs when it finishes. So, just add a callback to entry
:
class Customer
entry: (phone, req, callback = ->) ->
some_async_call phone, req, (arg, ...) -> callback(other_arg, ...)
I don't know what the arguments for some_async_call
's callback are or what you'd want to pass to entry
's callback so I'm using arg, ...
and other_arg, ...
as illustrative placeholders. If the arguments for some_async_call
and the entry
callback were the same then you could (as Aaron Dufour notes in the comments) just say:
entry: (phone, req, callback = ->) ->
some_async_call phone, req, callback
And then move the db.Entry.findOne
call into the callback thusly:
c = new Customer
c.entry phone, req, ->
db.Entry.findOne {x: req.body.x}, (err, entry) ->
The details inside entry
and the callback arguments would, of course, depend on what entry
is doing and what some_async_call
really is.
Any time you need to wait for something to happen in async (Java|Coffee)Script, you almost always solve the problem by adding a callback.
Upvotes: 4