设置变量以使用promise从回调函数返回 [英] setting a variable to get return from call back function using promise

查看:238
本文介绍了设置变量以使用promise从回调函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到对象值,而不是确切的值。
如何使用回调函数获取返回值?

I am getting the "object" value instead of the exact value. How to get return value using call back 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:

>

您的上述代码与延迟对象,创建框,并让你知道,在将来的某个时候你可以打开它。那个时候是上面的代码会调用 .resolve

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.

当您执行 results = loadDB(2)时,您正在将结果。

When you do results = loadDB(2) you are putting a box in results.

promise也有一个方法打开框,对值进行处理,并返回另一个值对框(同时打开任何附加框)。该方法是 .then

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:

在框中,它会:

> =>(。>> )=>

=>( . => ) =>

也就是说,它需要盒子,打开它并应用对其中的值执行某种操作的函数,然后返回另一个带有新值的框。

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.

所以,如果你想处理这个值,你需要在框打开的地方挂钩,像Bergi建议的:

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

这篇关于设置变量以使用promise从回调函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆