AngularJS $q.defer 延迟对象实例

前端之家收集整理的这篇文章主要介绍了AngularJS $q.defer 延迟对象实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、介绍

var deferred = $q.defer();// 声明延后执行,表示要去监控后面的执行

deferred.resolve(data);  // 声明执行成功,即http请求数据成功,可以返回数据了

deferred.reject(data);   // 声明执行失败,即服务器返回错误

return deferred.promise;   // 返回承诺,这里并不是最终数据,而是访问最终数据的API

2、方法定义

var getList = function () {
    var result = [];
    var allData = [];
    var parentData = [];

    var deferred = $q.defer();

    var db = window.sqlitePlugin.openDatabase({ name: 'xunhu.db',location: 'default' });
    db.transaction(function (tx) {
        tx.executesql('SELECT * FROM ShoppingCart',[],function (tx,rs) {
            for (var i = 0; i < rs.rows.length; i++) {
                allData.push(rs.rows.item(i));
            }
            //alert(allData.length);
        });
        tx.executesql('SELECT DISTINCT(VendorId),VendorName FROM ShoppingCart',rs) {
            for (var j = 0; j < rs.rows.length; j++) {
                parentData.push(rs.rows.item(j));
            }
            //alert(parentData.length);
        });
    },function (error) {
        deferred.reject(error);
        console.log('transaction error: ' + error.message);
    },function () {
        var jsonData = _.map(parentData,function (obj) {
            var child = _.filter(allData,function (o) {
                o.checked = false;
                return o.VendorId == obj.VendorId;
            })
            obj.childList = child;
            return obj;
            //delete obj.child
        });
        deferred.resolve(jsonData);
    });
    return deferred.promise;
}

3、调用

$scope.$on("$ionicView.beforeEnter",function () {
    getList().then(function (response) {
        $rootScope.shoppingCartList = response;
    },function (error) {
        alert(123);
    });
});

猜你在找的Angularjs相关文章