Tuesday 30 May 2017

How to deal with nested mysql queries in Node.js - my solution

I would like to ask you if my solution of dealing with nested mysql queries in Node js is proper, fast and elegant. When I have to do some nested queries I simply use Promise and Promise.all like below:

//beginning transaction, query = 'some insert'
//...
    _database.getConnection().query(query, [parent, name, user], (err, insert) => {
        if(err) rollback('TEST_CASE_ADD_ERROR')
        else {
            var id = insert.insertId
            var promises = []

            for(var flag of flags) {
                promises.push(new Promise((resolve, reject) => {
                    var query = `insert into flags (id_feature_flag, id_test_case, value)
                                values (?,?,?)`

                    _database.getConnection().query(query, [flag.id, id, flag.value], (err, insert) => {
                        if(err) reject('ADD_FEATURE_FLAG_TO_TEST_CASE_ERROR')

                        resolve(true)
                    })
                }))                       
            }

            Promise.all(promises).then(result => {
                _database.getConnection().commit(err => {
                    if(err) rollback(err)

                    resolve('TEST_CASE_ADDED')
                })
            }).catch(err => {
                rollback(err)
            })
        }
    })

As we know, query method is async so sometimes when I need to add many records at once to particular id, or select it I can use promise and wait until all promises are resolved. Is it a good way?

Regards



via Michal Bialek

No comments:

Post a Comment