I've problem sync here?


#1

Hi all.
I’m studying the technology and learning alone because I can not find anyone who knows Ionic here in my city.
And now I have this problem with SqlLite return data to a list.
This is my code problem:

self.getList = function() {
var items =[];
console.log(" do before 1 *******");
DBA.query(“SELECT key, name FROM table”).then(function(result) {
items = DBA.getAll(result); // here i stringify
console.log(" do after *******");
console.log(" do after items="+items);
});
console.log(" do before 2 *******");
console.log(" do before 2 items="+items);
console.log(" ");
return items; // Return nothing
}

The console show this:
do before 1 *******
do before 2 *******
do before 2 items= // nothing show here

do after *******
do after items=[{“key”:“1”,“name”:“ONE”},{“key”:“2”,“name”:“TWO”}]

If I change the return items; to return [{“key”:“1”,“name”:“ONE”},{“key”:“2”,“name”:“TWO”}]; works fine.

I google this and found .resolve but did not understand how that works.

Any help would be good, because I’m stoped here for days
Thanks in advance.


#2

Unless I did not understand your issue, there’s nothing weird here.
That’s just the way promises work, it’s not only related to SQLite.
Google for ‘JavaScript Promises’.


#3

Yup! You gave me the light!
The correct code is:

self.getList = function() {
var items =[];
var q = $q.defer();
DBA.query(“SELECT key, name FROM table”).
then(function(result){
items = DBA.getAll(result);
q.resolve(items);
});
return q.promise;
}

Thank you.