Returning values from nested functions in Javascript [duplicate]
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!
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;
}
function getSecret() {
var retval = undefined; // or a reasonable default
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;
retval = secret;
}, errorHandler
);
}
)
return retval;
}
This will create a closure over the retval
variable. When transaction
is called, retval
will be updated.