Pie*_*rre 4 javascript html5 opendatabase
我写了以下内容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');
}
);
});
};
Run Code Online (Sandbox Code Playgroud)
我想return的true还是false值tableFilled().
实际上是that.tableFilled('tableName')回归undefined.
我最终想要实现的目标是:
if ( that.tableFilled('tableName') ){
// ...
}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以return在不使用回调的情况下对父函数进行true或false值?tableFilled()
您正在处理异步进程,因此无法直接返回值.
你可以不过做的是返回一个承诺.您的功能将承诺在可用时为您提供该值.要从承诺中获取值,您必须添加回调函数.
您仍然需要使用回调函数,但不再需要嵌套函数,只需序列化它们即可.
这可能超出了您当前需求的范围,但这是一个非常有趣的概念.如果你想了解更多信息,只需谷歌吧.
这是一个简短的例子:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3670 次 |
| 最近记录: |