如何将函数内的值返回给另一个函数?

时间:2014-07-30 14:21:37

标签: javascript angularjs

到目前为止,我没有遇到任何问题,并认为我可以稍微处理一下AngularJS 但是现在我试图返回一个没有任何结果的值 第三行调用我的函数从数据库中获取名称。但该功能不会返回结果。

$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(),我会在控制台中获得一个值。但为什么我不能把我的结果带回调用函数?

4 个答案:

答案 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
                }                      
            );
        }
    );
}
相关问题