简体   繁体   中英

JavaScript async callbacks

I have some code that selects values from a WEB SQL database, which is done with the following code:

db.transaction(function(tx) {
            tx.executeSql(query, params_array, result, error);
        });

In the callback function "result" I simply return the affected rows to the function that called db.transaction()

The call looks like this:

database.select(<some params, not imporntant for now>, function(result){
//do stuff
}

if I call it once I get exactly the output from the db that I expected, but when I do this call multiple times, only the callback function of the last call will be executed (I tried anonymous and named callback functions).

How can I make this asyncronous calls work without nesting the callbacks into each other like this:

database.select(<some params>, function(result){
    //do stuff
    //call again
    database.select(<some params>, function(result){
        //and so on...
    });
}); 

You can name your functions but this is 10x less readable :D

database.select(<some params>, first);

function first(result) {
    //do stuff
    //call again
    database.select(<some params>, second);
}

function second() {
    //and so on...
}

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