2

I am querying dexie database with startsWithIgnoreCase and push result in an array but while printing or using it, it is throwing an error as undefined

I have tried using JSON.stringify, toString, String to convert it in a string and print on console but still it showing undefined

While print whole array to console showing normal Array()

arr = [];
db.table('friends').where('name').startsWithIgnoreCase('DoB/')
                    .each(function (friend) {
                        arr.push(String(friend.name));
                    });
console.log(arr[0]); //undefined 
console.log(arr); //Array() with correct element inside

I should at least print something when i use console.log(arr[0])

AtiqGauri
  • 1,483
  • 13
  • 26
  • of course, you cant see arr[0] in console.log() cause invoking database queries always are asynchronous .try to wrap your query in promise or async/await – Babak Abadkheir Oct 31 '19 at 17:11
  • I am sorry if this is silly to ask but ( new to javascript ) I am pushing element inside array which is showing correctly. when I use console.log(arr) print show correct element inside array but console.log(arr[0]) don't – AtiqGauri Oct 31 '19 at 17:15
  • can you show me how I can do it – AtiqGauri Oct 31 '19 at 17:17
  • [The console evaluates the array lazily](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) that's why you see array is "full" yet `arr[0]` is not there. `console.log(JSON.stringify(JSON.parse(arr)))`, so you log a copy of what is in `arr` at that point and you'll see it's empty. – VLAZ Oct 31 '19 at 17:21

1 Answers1

2

invoking data from database, is something asynchronous and javascript is not waiting for you till your task be done unless you told it. use async/await in your query. something like this:

async myControllerFunction()=>{
    arr = [];
    let firends = await db.table('friends').where('name').startsWithIgnoreCase('DoB/')
        .each(function (friend) {
            arr.push(String(friend.name));
        });
    console.log(arr[0]);
    console.log(arr);
}
Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46