Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 389
nukl Avatar asked Aug 25 '11 21:08

nukl


People also ask

Can we return value from async function?

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.

How do I get data from async function in react?

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 }); };

Is fetch an async function?

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.


1 Answers

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 */
});
like image 189
Ben Lee Avatar answered Sep 20 '22 16:09

Ben Lee