[英]Returning a value from a nested function to it's parent without using a callback
I wrote the following function
to check if my HTML5 openDatabase
table is filled or empty: 我编写了以下function
来检查我的HTML5 openDatabase
表是填充还是空:
var that = this;
that.db = openDatabase('dbname', '1.0', "description", 1024 * 1024);
that.tableFilled = function( tableName ) {
that.db.transaction(function ( tx ) {
tx.executeSql('SELECT * FROM ' + tableName, [],
function success( c, results ) {
return ( results.rows.length > 0 ? true : false );
},
function fail() {
console.log('FAiL');
}
);
});
};
I am trying to return
the true
or false
values to tableFilled()
. 我试图将true
或false
值return
到tableFilled()
。
Actually that.tableFilled('tableName')
returns undefined
. 实际上that.tableFilled('tableName')
返回undefined
。
What I am trying to achieve at the end is: 我最终想要实现的目标是:
if ( that.tableFilled('tableName') ){
// ...
}
Is there a way I can return
the true
or false
values to the parent function tableFilled()
without using a callback ? 有没有办法可以在不使用回调的情况下将true
或false
值return
到父函数tableFilled()
?
You're dealing with an asynchronous process so you can't return a value directly. 您正在处理异步进程,因此无法直接返回值。
What you can do however is return a promise . 但是什么你能做的就是回报的承诺 。 Your function will promise to give you that value when it's available. 您的功能将承诺在可用时为您提供该值。 To get the value out of the promise, you have to add a callback function. 要从承诺中获取值,您必须添加回调函数。
You still need to use a callback function but you don't need to nest your functions anymore, you can just serialize them. 您仍然需要使用回调函数,但不再需要嵌套函数,只需序列化它们即可。
This may be way out of scope for your current needs but it's a very interesting concept. 这可能超出了您当前需求的范围,但这是一个非常有趣的概念。 Just Google for it if you want to know more. 如果你想了解更多信息,只需谷歌吧。
Here is a short example: 这是一个简短的例子:
function my_function() {
var promise = new_promise();
do_asynchronous(function callback(result) {
promise.resolve(result); // gets called after 1 second
});
return promise;
}
var promise = my_function();
promise.done(function(result) {
console.log(result); // prints "yay!" after 1 second
});
function new_promise() {
var handlers = [];
return {
"resolve": function (result) {
for (var i = 0; i < handlers.length; i += 1) {
handlers[i](result);
}
},
"done": function (a_callback) {
handlers.push(a_callback);
}
};
}
function do_asynchronous(callback) {
setTimeout(function () {
callback("yay!");
}, 1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.