1 Introduction
var deferred = $q.defer();// Deferred execution is declared, indicating that it is necessary to monitor subsequent executions deferred.resolve(data); // The statement is executed successfully, that is, the http request data is successful, and the data can be returned deferred.reject(data); // The statement failed to execute, that is, the server returned an error return deferred.promise; // Return the promise, this is not the final data, but the API to access the final data
2. Method definition
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', [], function (tx, 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. Call
$scope.$on("$ionicView.beforeEnter", function () { getList().then(function (response) { $rootScope.shoppingCartList = response; }, function (error) { alert(123); }); });