0

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)
    }
}
NowUserID
  • 3
  • 3
  • Your code is asynchronous. In other words, you have to wait until the callback executes. It may not do so immediately. That callback will happen later, after the IO associated with the query has completed. Do you understand how to use promises or async/await in JavaScript? See [Use promise to process MySQL return value in node.js](https://stackoverflow.com/questions/36547292/use-promise-to-process-mysql-return-value-in-node-js) for more info. – Wyck Oct 16 '22 at 16:16
  • `i <= array.length` is a common [off-by-one error](/q/2939869/4642212) and should be `i < array.length`, or in your case: `i < dataMainIndexLength`. Other than that, please see [How do I convert an existing callback API to promises?](/q/22519784/4642212) and [How do I return the response from an asynchronous call?](/q/14220321/4642212). You already have an `async` function, so call `pdo.query` in a Promise, resolve it in the callback, return the result, await the call. Use [Promise methods](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise#static_methods). Try it. – Sebastian Simon Oct 16 '22 at 16:16
  • @SebastianSimon - if I use <= I get one record less – NowUserID Oct 16 '22 at 17:31

0 Answers0