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?
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.
export const getAllItems = async () => { const url = baseUrl + "/items/getAllItems"; await axios({ method: "GET", withCredentials: true, url: url, }). then((res) => { return res; // when console logged we get a proper array if data }); };
Fetch API is an asynchronous web API that comes with native JavaScript, and it returns the data in the form of promises. You use several Web APIs without knowing that they are APIs. One of them is the Fetch API, and it is used for making API requests.
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 */
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With