javascript 使用promise设置一个变量以从回调函数中获取返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22536385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:19:20  来源:igfitidea点击:

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

javascriptcallbackpromise

提问by Ananthan

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

回答by Benjamin Gruenbaum

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.

上面带有延迟对象的代码创建了框,并让您知道将来某个时间您可以打开它。那个时候就是上面的代码将调用.resolve.

When you do results = loadDB(2)you are putting a boxin 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). That method is .then:

一个promise还有一个方法可以打开盒子,处理值并返回另一个盒子的值(同时打开任何额外的盒子)。该方法是.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

回答by Bergi

You cannot get the resolve value outof a promise (here: asynchronous) context.

你不能得到的决心值一个承诺(在这里:异步)的范围内。

Instead, you will need to move the console.logcall and everything else that depends on it intothe promise context:

相反,您需要将console.log调用以及依赖于它的所有其他内容移动promise 上下文中:

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