I need to make two DB queries inside of async loops. I use node-mysql
and async.js
.
Here is an example of my code:
async.every(firstArray, (first, firstCB) => {
async.every(secondArray, (second, secondCB) => {
async.every(thirdArray, (third, thirdCB) => {
model.getUsers(third, (res) => {
model.insert(res.stuff, () => {
thirdCB()
})
})
}, (err) => {
secondCB()
});
}, (err) => {
thirdCB()
})
}, () => {
firstCB()
}, () => {
// done
})
The itereting works well. My problem is in the last loop where Im doing two queries: console.log .. considering thirdArray.length === 3
..getting users
..getting users
..getting users
..inserting stuff
..inserting stuff
..inserting stuff
Why so? Im calling the thirdCB after the second query recently.
I even tried with i.e. async.waterfall([getUser, insert], thirdCB)
but with the same result.
Thanks for any help!
After long research I found it!
The solution to this is using eachLimit
, setting the limit to 1
, instead of every
. That will limit the amount of async operation per item.