setting a variable to get return from call back function using promise

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);

Answers:

Answer

A promise is like a closed box:

enter image description here

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:

enter image description here =>( open. => e) => e

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
Answer

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);
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.