const getDbInfo = (anArrayOfIDs) => {
return new Promise(function(resolve, reject){
let arrayOfDbInfoToSendBack = [];
for(let i = 0; i <= anArrayOfIDs.length-1; i ){
pool.query(
"SELECT * FROM `tbl_ofInfo` WHERE tbl_ofInfo.sqlID = '"
anArrayOfIDs[i]
"';",
async(err, res) => {
if (err) {
console.log("error: ", err);
} else {
for(let k = 0; k <= res.length-1; k ){
arrayOfDbInfoToSendBack.push(res);
}
resolve(arrayOfDbInfoToSendBack);
}
}
);
}
});
}
Expected this function to return an array of objects with information. I suspect I am using resolve incorrectly and it sending back an array of only 1 object when I want an array of multiple objects in it.
CodePudding user response:
Does this piece of code work?
const getDbInfo = (anArrayOfIDs) => {
return new Promise(function(resolve, reject) {
pool.query("SELECT * FROM `tbl_ofInfo` WHERE tbl_ofInfo.sqlID IN (?)", anArrayOfIDs ,
(err, res) => {
if (err) {
console.log("error: ", err);
reject(err);
return;
}
resolve(res)
}
);
});
}
CodePudding user response:
If the one object that is being returned is correct one, then problem can be rooted back to the fact that you are resolving inside the for loop.
That means that only first iteration is called and then as promise has already resolved then next iterations are obsolete considering the callback nature of pool.query
i would assume that putting await before it can solve the problem
const getDbInfo = (anArrayOfIDs) => {
return new Promise(async function (resolve, reject) {
let arrayOfDbInfoToSendBack = [];
anArrayOfIDs.forEach(async (id) => {
await pool.query(
"SELECT * FROM `tbl_ofInfo` WHERE tbl_ofInfo.sqlID = '"
id
"';",
async (err, res) => {
if (err) {
console.log("error: ", err);
} else {
for (let k = 0; k <= res.length - 1; k ) {
arrayOfDbInfoToSendBack.push(res);
}
}
}
);
resolve(arrayOfDbInfoToSendBack);
});
});
}