I'm trying to use the best practics with Javascript but it's so hard for me.In this case I wanna use some function "avoid" the callbacks. I'm trying to use the Deferred object of jquery to do it. So I believe that I don't how to works fine.
I'm working with phonegap + emberjs + cordova-sqlite-plugin.
I've the follwing function that implements callbacks.
getPuntos: function(callback)
{
var db = window.sqlitePlugin.openDatabase("Rondas", "1.0", "Dev", -1);
var ret ={data:false};
db.transaction(function(tx)
{
tx.executeSql("SELECT * from Punto;",[], function(tx, res)
{
if( res.rows.length !== 0)
{
var puntos = [];
for( var i=0; i<res.rows.length; i++)
{
var descripcion = res.rows.item(i).descripcion;
var id = res.rows.item(i).id;
//console.log( descripcion );
var punto = App.Punto.create( { index: i, id:id, descripcion: descripcion});
puntos.push( punto );
}
ret.data = puntos;
callback(ret.data);
}
});
},function(tx,err){
console.log('Error SQL'+err);
},function(){
console.log( 'Base de datos abierta' );
});
}
and I use this as well:
this.getPuntos(function(puntos){
for( var i=0; i<puntos.length; i++){
console.log( puntos[i] );
}
});
Well, but I try to implements something very clear and easy like:
//whitout use a callback.
var puntos = this.getPuntos();
for( var i=0; i<puntos.length; i++){
console.log( puntos[i] );
}
Then I try to do it:
- Change the function
getPuntos
to_getPuntos
, this function has a deferred obeject. - the function
getPuntos
is wrapper to handle the result of promise getting in the method_getPuntos
and try to return.(but not works)
_getPuntos: function()
{
var db = window.sqlitePlugin.openDatabase("Rondas", "1.0", "Dev", -1);
var deferred = jQuery.Deferred();
var ret ={data:false};
db.transaction(function(tx)
{
tx.executeSql("SELECT * from Punto;",[], function(tx, res)
{
if( res.rows.length !== 0)
{
var puntos = [];
for( var i=0; i<res.rows.length; i++)
{
var descripcion = res.rows.item(i).descripcion;
var id = res.rows.item(i).id;
//console.log( descripcion );
var punto = App.Punto.create( { index: i, id:id, descripcion: descripcion});
puntos.push( punto );
}
//ret.data = puntos;
//callback(ret.data);
deferred.resolve(puntos);
}
});
},function(tx,err){
console.log('Error SQL'+err);
},function(){
console.log( 'Base de datos abierta' );
});
return deferred.promise();
},
The wrapper:
getPuntos: function()
{
var promise = this._getPuntos();
var ret = {data:false};
promise.done(function(result)
{
ret.data = result;
return ret.data;
});
while(ret.data ===false ){} //wait for the result until it's available
return ret.data;
},
In the main function I call it :
var puntos = this.getPuntos();
console.log( puntos+"--shoulbe [object]"); //I get Undefined or false, but no my array.
So, is there some way to do that I wanna, convert a asynchronous function in synchronous function?.
Thanks for all your answers.