getting data from async function
i have this code:
function getData(){
db.transaction(function(tx){
tx.executeSql('SELECT * from q', [], function(tx, result){
var q = [];
for (var i=0; i < result.rows.length; i++) {
q.push(result.rows.item(i));
开发者_如何学运维 };
console.log(q.length); // 3
returnData(q);
});
});
}
function returnData(data){
console.log(data.length); // 3
return data;
}
var q = getData(); // undefined
and it don't work as expected (it don't return anything). A assume that happened, because db.transaction
work asynchronous, but i'm using callback to return data. Can somebody explain why it doesn't work and how to fix that?
The standard way to do this is to include your own callback, like this:
function getData(callback){
db.transaction(function(tx){
tx.executeSql('SELECT * from q', [], function(tx, result){
var q = [];
for (var i=0; i < result.rows.length; i++) {
q.push(result.rows.item(i));
};
console.log(q.length); // 3
callback(returnData(q));
});
});
}
function returnData(data){
console.log(data.length); // 3
return data;
}
getData(function(q) {
/* do something with q */
});
You don't return the result of any async action, instead you listen for it.
In your code returnData
does return the data, but the you dont do anything with the result, it's discarded. Instead, you should use your own callback.
function getData(callback){
db.transaction(function(tx){
tx.executeSql('SELECT * from q', [], function(tx, result){
var q = [];
for (var i=0; i < result.rows.length; i++) {
q.push(result.rows.item(i));
};
console.log(q.length); // 3
callback(q);
});
});
}
var q;
getData(function(data) {
console.log(data.length); // 3
console.log(data);
doStuffWith(data);
q = data;
});
精彩评论