Pete Pete - 29 days ago 9
Javascript Question

Returning values from nested functions in Javascript

Consider this code (shortened)

function getSecret() {
db.transaction(
function (transaction) {
transaction.executeSql(
'SELECT * FROM table LIMIT 1;',
null,
function(transaction, result) {
var row = result.rows.item(0);
var secret = row.secret;
return secret;
}, errorHandler
);
}
)
}


How would I return the value of secret to the main function? I have read this answer Return value from nested function in Javascript

And tried this

function getSecret() {
db.transaction(
function doSql(transaction) {
transaction.executeSql(
'SELECT * FROM table LIMIT 1;',
null,
function(transaction, result) {
var row = result.rows.item(0);
var secret = row.secret;
return secret;
}, errorHandler
);
}
)
return doSql;
}


However this did not work.

Thanks!

Answer

Try:

function getSecret() {
    var secret = '';

    db.transaction(
        function (transaction) {
            transaction.executeSql(
                'SELECT * FROM table LIMIT 1;',
                null,
                function(transaction, result) {
                    var row = result.rows.item(0);
                    secret = row.secret;
                }, errorHandler
            );
        }
    )

  return secret;
}