Ivaylo Nikolov
Ivaylo Nikolov

Reputation: 15

How do I make for loop wait for db promise to finish before it continues to next iteration?

Im currently using node.js sequalize to extract data from database and in the frontend I am using ajax requests. So I am sending ajax request with json object to edit the database. But when I try to edit the database the foor loop doesnt wait for the promises to finish before it goes to next iteration. I tried to send the promises to array and using the Bluebird function Promise.each but the promises are executed before they are even sent to the array. What can I do so I can pause the for loop before the current promise is completed?

for(var i=0; i<recordsJSON.length; i++)
{
    var recordJSON = recordsJSON[i];

    Record.nullPayeeId(recordJSON.id).then(function()
    {
        return Record.getOneRecord(recordJSON.id);
    })
    .then(function(record)
    {
        var virtualPayeeId = record.virtualPayeeId;
        return VirtualPayee.deletePayee(virtualPayeeId);
    })
    .then(function()
    {
        var category = parseInt(recordsJSON[i].category);
        var subcategory = parseInt(recordsJSON[i].subcategory);

        return VirtualPayee.insertPayee({
            payee: recordJSON.payee,
            description: recordJSON.description,
            categoryId:category,
            subcategoryId:subcategory
        })
    })
}

Upvotes: 0

Views: 147

Answers (1)

jfriend00
jfriend00

Reputation: 707696

Since you meantioned Bluebird, you can use Promise.mapSeries() to help you serialize things:

Promise.mapSeries(recordsJSON, function(recordJSON) {
    return Record.nullPayeeId(recordJSON.id).then(function () {
        return Record.getOneRecord(recordJSON.id);
    }).then(function(record) {
        var virtualPayeeId = record.virtualPayeeId;
        return VirtualPayee.deletePayee(virtualPayeeId);
    }).then(function() {
        var category = parseInt(recordJSON.category);
        var subcategory = parseInt(recordsSON.subcategory);

        return VirtualPayee.insertPayee({
            payee: recordJSON.payee,
            description: recordJSON.description,
            categoryId: category,
            subcategoryId: subcategory
        });
    });
}).then(function (results) {
    // results here in oder
}).catch(function (err) {
    // error here
});

If you want to serialize them manually, then you would probably want to use the .reduce() pattern with your promises. You can read about that pattern here:

JavaScript: Perform a chain of promises synchronously

How to synchronize a sequence of promises?

Can Promise load multi urls in order?

Upvotes: 2

Related Questions