Node.js:确保一段代码一段接一段地执行

Node.js: Make sure a piece of code is executed after another

本文关键字:一段 执行 代码 js Node 确保      更新时间:2023-09-26

给定此代码:

 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) ->

我如何确保数据库。Entry.findOne仅在c.Entry完成后执行?

class Customer
  entry: (phone,req) ->

假设您的entry方法执行异步操作,并且something应该有一个在完成时运行的回调。所以,只需在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_callentry回调的参数相同,那么您可以(正如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到底是什么

任何时候,当您需要在async(Java|Coffee)Script中等待某件事发生时,您几乎总是通过添加回调来解决问题。