I would like with my array works outside of my for loop but my array is empty:
let dataSitesIndex = [];
for(let i = 1; i <= dataMainIndexLength; i++){
pdo.query("SELECT * FROM subsites WHERE main = ?",[i] , function(err, result, fields) {
dataSitesIndex[i] = result;
console.log(result);
})
}
let dataLength = async function(){
try {
//Durchsuchen der Nachrichtenseite, speichern der MainID
pdo.query(`SELECT * FROM mainsites`, function(err, result, fields) {
let results = result;
let resultsLength = results.length;
//MainID
let dataIndexMainId = [];
for(let index = 0; index < resultsLength; index++){
dataIndexMainId[index] = results[index]["id"];
}
let dataMainIndexLength = dataIndexMainId.length;
let dataSitesIndex = [];
for(let i = 1; i <= dataMainIndexLength; i++){
pdo.query("SELECT * FROM subsites WHERE main = ?",[i] , function(err, result, fields) {
dataSitesIndex[i] = result;
console.log(result);
})
}
})
} catch(error) {
console.log(error)
}
}
i <= array.lengthis a common off-by-one error and should bei < array.length, or in your case:i < dataMainIndexLength. Other than that, please see How do I convert an existing callback API to promises? and How do I return the response from an asynchronous call?. You already have anasyncfunction, so callpdo.queryin a Promise, resolve it in the callback, return the result, await the call. Use Promise methods. Try it.