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!
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
You can't, it is only possible once.
Function as Return Value of FunctionA JavaScript function can be passed as a return value from another function.
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.
Try promisifying the database operation before returning your payload.
Additionally, you can use promise's built in reject() as an error handler, returning the transaction object whenever the function returns undefined.
Declare promise within function:
function getSecret() {
var secret = '';
return new Promise(function(resolve, reject) {
db.transaction(
function(transaction) {
transaction.executeSql(
'SELECT * FROM table LIMIT 1;',
null,
function(transaction, result) {
if (typeof(result) === 'undefined') {
var row = result.rows.item(0);
secret = row.secret;
resolve(secret)
},
else {
reject(transaction)
}
}
);
}
)
})
}
Then call the function.
//If function resolves, log the secret.
//if function rejects, log the transaction
getSecret().then(function(secret) {
console.log(secret);
})
.catch(function(err) {
console.log('Error in db.transaction ' + err)
})
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With