How to wait till callback function returns?

2019-02-23 10:29发布

I'm making an android application using phonegap. I'm using phonegap's Storage api for querying a database. here's my code:

function directPath(src, dest)
{
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
    db.transaction(queryDB, errorCB);
    return arrayroute;
}

function queryDB(tx)
{
    tx.executeSql(query, [], querySuccess, errorCB);
}

function querySuccess(tx,results) {
    //Write some code here.
}

function errorCB(err) {
    alert("Error in SQL: " + err);
}

The problem is I want to wait till the callback method querySuccess finishes execution before returning from the directPath method.

3条回答
Animai°情兽
2楼-- · 2019-02-23 10:53

I wrote a function to solve a similar problem, you can call it like this:

database("SELECT * FROM USER", function(result){
    console.log(result);
});

//FUNCTION
function database(sql, callback) {

    if(!callback) { callback = function(r) { console.log(r); } }

    var database_name = "Database",
        database_version = "1.0",
        database_displayname = "DatabaseName",
        database_size = 1000000,
        result = {
            error: -1,
            message: "",
            len: 0,
            rows: {}
        },
        db = window.openDatabase(database_name, database_version, database_displayname, database_size);
        db.transaction(
                        function (tx) {
                            tx.executeSql(sql, [], querySuccess, errorCB);
                        }, function (tx, results) {
                            //SUCCESS
                        }, function (err) {
                            //ERROR
                        }
        );
        function querySuccess(tx, results) {
            if (results) {
                result.len = results.rows.length;
                result.message = "Success";
                for (var i=0; i<result.len; i++){
                    result.rows[i] = results.rows.item(i);
                }
            } else {
                result.len = 0;   
            }
            callback( result );
        }
        function errorCB(err) {
            result.error = err.code;
            result.message = err.message;
            callback( result );
        }
}
查看更多
ら.Afraid
3楼-- · 2019-02-23 10:55

Don't try to fight the asynchrony: Your app might end up seeming unresponsive to the user. Use the querySuccess callback for any code that has to be executed afterwards.

查看更多
霸刀☆藐视天下
4楼-- · 2019-02-23 11:01

You don't have to wait... Just write your code in querySuccess to execute it afterwards....

查看更多
登录 后发表回答