Pergunta

I need to execute a series of MySQL inserts in a loop, and then do something after they are all completed. However, I'm not sure where to put the callback --

for (var q=0; q<things.length; q++)
{

thing
    .create({
        active_time: time
        rule: rule
        next: next_object,
        percentage: object.percent,
        enabled: 1,
    })
    .complete(function(err, newSchedule) {
        console.log('thing added successfully');

    })

}

I can't put it in the .complete section, because it needs to occur after all of them. How can I ensure that they are all done before proceeding?

EDIT: I've started using AsyncJS but it seems that the MySQL queries will callback before they are finished. Here is the new code:

if (valid) {

        async.each(arrayOfObjects, tools.submitThing, function()
        {
            console.log("finished submissions")
        });

and

exports.submitThing = function(thingObject, callback) {

   thing
    .create({
        active_time: time
        rule: rule
        next: next_object,
        percentage: object.percent,
        enabled: 1,
    })
    .complete(function(err, newSchedule) {
        console.log('thing added successfully');

    })

    callback();

}

The server console shows that the message "submissions completed" registers before the MySQL insertions. Any way to get around this?

Foi útil?

Solução

What you want is an asynchronous control flow library to handle executing a loop of asynchronous functions in order.

Check out the async npm module (docs) and especially the async.eachSeries function. This will let you loop over all of your things, and for each thing, run the create queries one-by-one. You'll then have a final callback function at the very end when they're all done inserting.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top