[英]Node.js: Make sure a piece of code is executed after another
給出以下代碼:
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) ->
大概您的entry
方法執行異步操作,並且某些操作應具有在完成時運行的回調。 因此,只需向entry
添加回調:
class Customer
entry: (phone, req, callback = ->) ->
some_async_call phone, req, (arg, ...) -> callback(other_arg, ...)
我不知道some_async_call
的回調的參數是什么,或者您想傳遞給entry
的回調的arg, ...
所以我使用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)腳本中發生的任何事情時,幾乎總是可以通過添加回調來解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.