I have a strange comportement with my code in Ionic : the code is not executed in the order.
In one function in my controller, i put several alerts to undesterand a bug, and an alert in the end of my method. The last alert is set before the alert I put at the start of my method when i test it. There is the code :
$scope.add = function()
{
Therefore, my bug come from this comportement, because i use a var that depends from a precedent request who is made after i need it… Do you have any idea about this ?
I think the reason is that queries are asynchronous, so they do not execute the code immediately but wait for data and running next code at the same time. this: https://docs.angularjs.org/api/ng/service/$q will help you.
I think your sql query is taking time for execution that’s why your second alert is appearing before first.
You can use $timeout for your query till the execution done.
Thanks, i will test with timeout, but is there any way to do it in another way, because sometimes, the timeout will not be enough (if my app have, for example, 1000000 lines in the database…), just in saying to the code : don’t execute until that is before you is finish ?
Do not under any circumstances use timeout for something like this!!!
You should look at @Adamxyz’s answer. Or just look at promises in general. You need to learn how asynchronous programming works. You’re using it in your code already but it’s clear you don’t understand it. Please read into it. Updated with code sample.
I have read the documentation and i think I master better the $q, but not perfectly apparently, because i still have a bug that i reall don’t understand…
Here is my new code :
function getSoldeUserAndSoldPeople(choice, id) {
return $q.all({soldeUser: getSoldeUser(choice), soldPeople: getSoldPeople(id)});
}
function getSoldeUser(choice) {
var query = "SELECT * FROM options WHERE name = ?";
return $cordovaSQLite.execute(db, query,[choice]).then(function(res) {
return parseFloat(res.rows.item(0).value);
});
}
function getSoldPeople(id) {
var query = "SELECT * FROM people WHERE id = ?";
$cordovaSQLite.execute(db, query, [id]).then(function(res) {
alert("in the matrice");
return res.rows.item(0).solde;
});
}
Hey looking good this is a big improvement! I believe your problem is that $q.all expects each value in the object passed in to be a promise, but because you are not returning a promise in getSoldPeople it’s not working properly. You need getSoldPeople to look like getSoldeUser above and actually return the promise itself like this:
function getSoldPeople(id) {
var query = "SELECT * FROM people WHERE id = ?";
return $cordovaSQLite.execute(db, query, [id]).then(function(res) {
alert("in the matrice");
return res.rows.item(0).solde;
});
}
Notice the return before the $cordovaSQLite.execute. This way the promise itself is returned from the function, which is what $q needs. Good work on updating your code.