$scope.showModal = function ($event,listId) {
console.log("showModal: "+$event.type+" - id: "+listId);
console.log("scope.listname: "+getListname(listId));
$('#edit').modal('toggle');
};
function getListname(listId) {
var query = 'SELECT name FROM Lists WHERE id=(?)';
$scope.db.transaction(
function (transaction) {
transaction.executeSql(query, [listId],
function (tx, results) {
// console.log("Result: "+results.rows.item(0).name); // works!
return results.rows.item(0).name; // returns nothing or not to the sender
}
);
}
);
}
如果我在executeSql中使用console.log(),我会在控制台中获得一个值。但为什么我不能把我的结果带回调用函数?
答案 0 :(得分:2)
欢迎来到异步的世界! executeSql
是异步的,因此在该函数完成后使用回调来访问数据:
function getListname(listId, callback) {
var query = 'SELECT name FROM Lists WHERE id=(?)';
$scope.db.transaction(
function (transaction) {
transaction.executeSql(query, [listId],
function (tx, results) {
// console.log("Result: "+results.rows.item(0).name); // works!
callback(results.rows.item(0).name); // returns nothing or not to the sender
}
);
}
);
然后打电话给它!
getListName(listId, function(name) {
console.log(name);
});
答案 1 :(得分:1)
您应该使用promise以同步方式编写代码,但在异步中执行它。 https://docs.angularjs.org/api/ng/service/ $ Q
答案 2 :(得分:1)
function getListname(listId) {
var query = 'SELECT name FROM Lists WHERE id=(?)';
var deferred = $q.defer();
transaction.executeSql(query, [listId],
function (tx, results) {
deferred.resolve(results.rows.item(0).name);
}
);
return deferred.promise;
}
可以像这样使用
getListname(listId).then(function(name){
$scope.db.transaction = name;
});
答案 3 :(得分:0)
您的请求是异步的,因此您应该使用回调处理它:
function getListname(listId, callback) {
var query = 'SELECT name FROM Lists WHERE id=(?)';
$scope.db.transaction(
function (transaction) {
transaction.executeSql(query, [listId],
function (tx, results) {
// console.log("Result: "+results.rows.item(0).name); // works!
callback(results.rows.item(0).name); // returns nothing or not to the sender
}
);
}
);
}