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

查看:24
本文介绍了使用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:

您上面的带有延迟对象的代码创建了框,并让您知道在将来的某个时间您可以打开它.那个时候就是上面的代码将调用 .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.

所以,如果你想处理这个值,你需要钩住那个盒子打开的地方,就像贝尔吉建议的那样:

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天全站免登陆