javascript - how to make a function that returns sql result set with jQuery? -
i want make function return value of sql result set list (datalite).the problem is, can't read value of variable(datalite) outside db.transaction
, return null
value . new javascript , jquery hope can find answer here. here's part of function
function functiona(){ var datalite=null; db.transaction(function (tx) { tx.executesql('select * tablea', [], function (tx, results) { var len = results.rows.length, i; msg = "<p>found rows: " + len + "</p>"; alert(msg); datalite=results.rows; }, null); }); alert(datalite+'>>>'); return datalite; }
you can't return asynchronous code, data not yet available when function returns, come later. such situations (ajax requests, animations, etc.) have patterns. 1 callbacks:
function functiona(callback) { db.transaction(function (tx) { tx.executesql('select * tablea', [], function (tx, results) { callback(results.rows); }, null); }); } functiona(function(data) { console.log(data); });
the second 1 promise pattern:
function functiona(callback) { return new promise(function(resolve) { db.transaction(function (tx) { tx.executesql('select * tablea', [], function (tx, results) { resolve(results.rows); }, null); }); }); } functiona().then(function(data) { console.log(data); });
the second 1 more powerful , advanced, , gives several additional benefits simple callback don't offer. in basic case both work fine.
also make sure read this post on similar topic.
Comments
Post a Comment