Andrew Font
Andrew Font

Reputation: 1285

Getting a function to wait for a post middleware save to finish before continuing

Here is my problem i have one worker running that gathers up some data and then saves it to a schema. In those schemas i have post middleware functions that happen on a save. The problem is that my worker does not wait for the post middleware to finish working before it loops and saves again to the same schema. As my worker continues to run it slows down substantially as it queues up those functions over and over again before this get to finish. Those post middleware functions also save to other schemas which also execute there own post functions. SO as i you can tell that starts to really slow down as i am dealing with hundreds of thousands of objects being saved.

Example of what my code kind of looks likes:

Worker

tranFunc = (stuff, Object) -> 
            newObject = Object
            newObject = new Object newObject
            newObject.save (err) ->

The Save now jumps into the schema where some more stuff happens, but my worker loops before that one is done and keeps going

Schema

ObjectSchema.post("save", function() {
 DOING STUFF

I have read that i could maybe use something like a next() as a callback to the worker but my attempts at using it were not successful.

Upvotes: 0

Views: 303

Answers (1)

hugomg
hugomg

Reputation: 69944

I don't think I can answer this question in its current form but the basic idea is that

  1. Async functions should use callbacks to communicate when they are done
  2. Functions that call async code are be async themselves.

So in your case, it looks like the worker function is violating this principle, since its calling an async function without being async itself. You would fix this by adding a return callback as a parameter and calling said callbabk after everything is done (that is, inside the callback for the last async method you call)

//sort of like this:
tranFunc = (stuff, Object, doneCb) -> 
        newObject = Object
        newObject = new Object newObject
        newObject.save (err) ->
            doneCb( /*put return values here as appropriate*/ )

Now whoever is calling tranFunc will be able to know when the inner save method has finished.

Upvotes: 1

Related Questions