简体   繁体   中英

Take out sqlresultset from a function using javascript websql

I have this function in my project. It should return result of a select request but it can not do it! jResult come out empty from transaction function. In first console.log it is ok and I can check the content but at the end it is empty!! So I can not return the result of my query.

Any one know what is the problem? Is there a better way to return sqlresultset from this function?

Thanks

function getHistoryList() { 
    var jResult=[];
    db.transaction( 
    function(transaction) { 
    transaction.executeSql( 'SELECT * FROM HISTORY;',[], 
                            function (transaction, result) { 
                            console.log("Query Success");
                            for (var i=0; i < result.rows.length; i++) { 
                                jResult.push(result.rows.item(i));
                                } 
console.log(jResult);
                            },
                            function (transaction, error) {
                                console.log("Query Error: " + error.message); 
                                }
                            ); 
                        },

    function (error) {
        console.log("Transaction Error: " + error.message);
    },
    function () {
        console.log("Transaction Success");
    } 
    ); 


console.log(jResult);
return jResult;  //  -> [] always
}

Functions transaction() and executeSql() are asynchronous . That means that the code after these functions can be executed before the sql transactions are performed.

That's why these function take in parameter callback functions. These functions are executed when the asynchronous function finish its work.

The reason why the first console.log works is that it is executed in the callback function : after the sql request have been performed.

So, if you want to exploit the result from a request, you must do this in the callback function you pass in parameter of the asynchronous function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM