Saturday 6 May 2017

Javascript/Node.js async loop

I'm having trouble with the async nature of node in general. Can someone help me with this block of code. For various reasons I can only insert 1 row at a time into the database I am working with. And actually, it would be even better if I could add a short delay to only insert 1 row per second into the database.

Here is a short section of my js code.

console.log('*** Inserting Records ***')
insertPromises = []
_.each(dbRecords, function (item) {
    var insertItem = buildRecord(item)
    insertPromises.push(conn.create(insertItem))
})
Promise.all(insertPromises).then(function (res) {
    _.each(res, function (item) {
        if (!item.success) {
            console.log("### Error ### " + JSON.stringify(res[i].errors))
        }
    })
    console.log('*** Inserted ' + res.length + ' Contacts')
})

My main question is how can I force the loop to wait for the conn.create promise to resolve before continuing the loop? And is there a way to slow the loop to 1 iteration per second?



via Todd

No comments:

Post a Comment