简体   繁体   中英

Returning a variable from a function

Here is a very easy one I guess (but JS is not my best friend and I'm stuck...)

How can I return the rows value ? (which is undefined...)

function myFunction(table){
    html5sql.process(
    ["SELECT * FROM "+table],
    function(transaction, results, rowsArray){
        rows = rowsArray; // rows is defined here
    },
    function(error, statement){
    });
    return rows; // rows is not defined here :(
}

You're probably not going to be able to do that as you have things now. With JS being by default asynchronous, rows will be returned even before any of those callbacks run. Since the success callback is what sets rows , you'll always be returning an either unset or stale value.

(Note: i have never used html5sql. It might be that the library just presents an interface that looks async while somehow actually working synchronously. But if it does, it'd be quite unusual in that regard.)

One possible fix would be to take a callback yourself, that you call and pass the rows to once you get them.

function myFunction(callback){
    html5sql.process(
    ["SELECT * FROM "+table],
    function(transaction, results, rowsArray){
        callback(rowsArray);
    },
    function(error, statement){
    });
}

// and use it like this
myFunction(function(rows) {
    // do stuff with rows in here
});

Or, just use callback as the second arg to process , if you want to be lazy. Just know that it will be passing all three args, which the caller of this function shouldn't have to care about. :P

Declare rows before assigning it's value:

function myFunction(){
    var rows;
    html5sql.process(
    ["SELECT * FROM "+table],
    function(transaction, results, rowsArray){
        rows = rowsArray; // rows is defined here
    },
    function(error, statement){
    });
    return rows; // rows is not defined here :(
}

That changes the variable scope, and makes it visible and accessible outside inner function as well.

minor change...

function myFunction(){
    var rows;

    html5sql.process(
    ["SELECT * FROM "+table],
    function(transaction, results, rowsArray){
        rows = rowsArray;
    },
    function(error, statement){
    });
    return rows;
}

You're getting an undefined because you havent really defined it it - doing so at the beginning of the function will make it specific to that scope and should return properly.

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