I am getting the "object" value instead of the exact value. How do I get the value returned using a callback function?
function loadDB(option, callBack){
var dfd = new jQuery.Deferred(),
db = window.openDatabase('mydb', '1.0', 'Test DB', 1024*1024),
selectQuery = "SELECT log FROM LOGS WHERE id = ?";
db.transaction(function(tx){
tx.executeSql(selectQuery,[option],function(tx,results){
var retval;
if( results.rows.length ) {
retval = unescape(results.rows.item(0)['log']);
}
var returnValue = dfd.resolve(retval);
});
});
return dfd.promise();
}
results = loadDB(2).then(function(val){ return val; } );
console.log("response***",results);
When a callback function completes execution, it returns any return value that it might have to the DataBlade API, which invoked it.
To convert a callback into a promise, you need to return a promise. You run the code with the callback inside the promise. const readFilePromise = () => { return new Promise((resolve, reject) => { fs. readFile(filePath, options, (err, data) => { // ... }) }) }
To assign value from successful promise resolve to external variable with JavaScript, we use async and await. const myFunction = async () => { vm. feed = await getFeed(); // ... }; to get the resolve value of the promise returned by getFeed with await .
A promise is like a closed box:
Your above code with the deferred object, creates the box, and lets you know that some time in the future you can open it. That time is when that above code will call .resolve
.
When you do results = loadDB(2)
you are putting a box in results.
A promise also has a method that opens the box, works on the value and returns another box on the value (also opening any additional boxes along the way). That method is .then
:
In boxes, it does:
=>( . => ) =>
That is, it takes the box, opens it and applies a function that does something to the value in it and then returns another box with the new value on it.
So, if you want to process the value, you need to hook on the one place where the box is open, like Bergi suggested:
loadDB(2).then(function(val){
console.log("response***", val);
}); // this also returns a promise btw
You cannot get the resolve value out of a promise (here: asynchronous) context.
Instead, you will need to move the console.log
call and everything else that depends on it into the promise context:
loadDB(2).then(function(val){
console.log("response***", val);
});
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