给定以下代码:
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) ->如何确保仅在c.entry完成后才执行db.Entry.findOne?
class Customer
entry: (phone,req) ->发布于 2012-02-09 05:33:36
假设您的entry方法做了一些异步的事情,并且某些事情应该有一个回调,当它完成时会运行。因此,只需向entry添加一个回调
class Customer
entry: (phone, req, callback = ->) ->
some_async_call phone, req, (arg, ...) -> callback(other_arg, ...)我不知道some_async_call回调的参数是什么,也不知道您想要传递给entry的回调的参数是什么,所以我使用arg, ...和other_arg, ...作为说明性的占位符。如果some_async_call和entry回调的参数是相同的,那么您可以(正如Aaron Dufour在注释中指出的那样)简单地说:
entry: (phone, req, callback = ->) ->
some_async_call phone, req, callback然后将db.Entry.findOne调用移到回调中:
c = new Customer
c.entry phone, req, ->
db.Entry.findOne {x: req.body.x}, (err, entry) ->当然,entry中的细节和回调参数将取决于entry正在做什么以及some_async_call到底是什么。
任何时候你需要等待异步(Java|Coffee)脚本中发生的事情,你几乎总是通过添加一个回调来解决这个问题。
https://stackoverflow.com/questions/9200484
复制相似问题