Question

I work with the last beta version of Sails / Waterline for NodeJS, the association system isn't ready yet so i'm trying to find a way to populate datas from other models with a small trick.

For example, I got a "User" model which has many "Server", let's forget about waterline populate() which is for now quite bugued and find out how to do it manually in pseudo-code :

FIND USER THEN { // asynchronous

  LOOP XXX

    FIND (EACH) SERVER FROM ID { // asynchronous

     DO THINGS HERE

    }

  END LOOP

  THEN OUTPUT SOMETHING

}

I think you already understood the big problem i got. The "THEN OUTPUT SOMETHING" will output something before the loop is ended because it's asynchronous requests. I tried to check on async (with callbacks, but there's nowhere to put it here) or these kind of tools but it seems there is nothing to handle this typical case that will appear everywhere in my project ...

Any idea ? That's really a big problem for every project I could make in NodeJS and i'm sure i'm not alone in this case ...

Thanks ;)

Was it helpful?

Solution

You need to use recursion:

do = function(i, data, callback){
    // if the end is reached, call the callback
    if(data.length === i+1)
       return callback()
    obj = data[i]
    // DO SOMETHING
    i++;
    // call do with the next object
    do(i, data, callback)

}
do(0, [a, b, c], function(){
  THEN OUTPUT SOMETHING
});

So the same callback (OUTPUT SOMETHING) will be passed on do and when the end is reached, the callback will be executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top