简体   繁体   English

设置变量以使用promise从回调函数中获取收益

[英]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);

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 . 到那时上述代码将调用.resolve

When you do results = loadDB(2) you are putting a box in results. results = loadDB(2)时,将在结果中放入一个框

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). Promise还提供了一种方法,可以打开框,对值进行操作,然后在值上返回另一个框(也将在此过程中打开任何其他框)。 That method is .then : 那是.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: 因此,如果要处理该值,则需要像框Bergi所建议的那样,钩住框处于打开状态的一个位置。

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: 相反,您将需要将console.log调用以及所有依赖于它的其他东西移动 promise上下文中:

loadDB(2).then(function(val){
    console.log("response***", val);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM