Niraj
Niraj

Reputation: 163

AngularJS synchronous $http calls and database insertion

We are making android app in ionic, i am using cordova sqlite db. i am making multiple $http calls to get data from different api. i am inserting data of each api in database. the problem is that, when i am calling first api and inserting data in db, the next ajax is called before complete insertion of first api data. in ios platform it's initiating memory issue and closing the app forcefully. really looking forward for this issue to be solved from many days.

self.setApm_reference_t = function()
{
    $http.get(ApiEndpoint.url+'/references')
                  .success(function(response) {
                      console.log(JSON.stringify(response));
                      for(var i=0;i<response.length;i++){
                      $cordovaSQLite.execute(db, "INSERT INTO apm_reference_t (reference_id, apm_id, salutation, firstname_vc, middlename_vc, lastname_vc, designation_vc) VALUES(?, ?, ?, ?, ?, ?, ?)", [response[i].reference_id, response[i].apm_id, response[i].sal_vc, response[i].firstname_vc, response[i].middlename_vc, response[i].lastname_vc, response[i].designation_vc]).then(function(result){
        console.log("inserting in setApm_reference_t");
    },function(err){console.log(JSON.stringify(err));});
            if(i == response.length-1)
                {
                    self.setApm_contact_t();
                }
                      }
                      }).error(function(error){
        console.log(JSON.stringify(error));
        self.setApm_reference_t();
    });
},
self.setApm_contact_t = function()
{
    $http.get(ApiEndpoint.url+'/apmContacts')
          .success(function(response) {
              console.log(JSON.stringify(response));
              for(var i=0;i<response.length;i++){
                  $cordovaSQLite.execute(db, "INSERT INTO apm_contact_t (apm_contact_id, apm_id, tel_vc, reference_id) VALUES(?, ?, ?, ?)", [response[i].apm_contact_id, response[i].apm_id, response[i].tel_vc, response[i].reference_id]).then(function(result){
                        console.log("inserting in setApm_contact_t");
                    },function(err){console.log(JSON.stringify(err));});
                    if(i == response.length-1)
                    {
                        self.setDepartment_t();
                    }
                  }
              }).error(function(error){
        console.log(JSON.stringify(error));
        self.setApm_contact_t();
    });
},
self.setDepartment_t = function()
{
    $http.get(ApiEndpoint.url+'/departments')
          .success(function(response) {
              console.log(JSON.stringify(response));
              for(var i=0;i<response.length;i++)
              {
                  $cordovaSQLite.execute(db, "INSERT INTO department_t(department_id, departmentHeader_id, department_vc, departmentMr_vc, is_deleted) VALUES(?, ?, ?, ?, ?)", [response[i].id, response[i].departmentHeader_id, response[i].department, response[i].departmentMr, response[i].is_deleted]).then(function(result){
                        console.log("inserting in setDepartment_t");
                    },function(err){console.log(JSON.stringify(err));});
                    if(i == response.length-1)
                    {
                        self.setContact_t();
                    }
              }
              }).error(function(error){
        console.log(JSON.stringify(error));
        self.setDepartment_t();
    });
},
self.setContact_t = function()
{
    $http.get(ApiEndpoint.url+'/contacts')
          .success(function(response) {
              console.log(JSON.stringify(response));
              for(var i=0;i<response.length;i++){
                    if(response[i].insert_date == null)
                    {
                        response[i].insert_date = "0000-00-00 00:00:00";
                    }
                    $cordovaSQLite.execute(db, "INSERT INTO contact_t (contact_Id, name_VC,nameEn_VC, designation_short_VC, contact_IN, insert_date, update_date, delete_date, is_cmo) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", [response[i].id, response[i].name_VC, response[i].nameEn_VC, response[i].designation_short_VC, response[i].contact_IN,  response[i].insert_date, response[i].update_date, response[i].delete_date, response[i].is_cmo]).then(function(result){
                        console.log("inserting in setContact_t");
                    },function(err){console.log(JSON.stringify(err));});
                    if(i == response.length-1)
                    {
                        self.setApm_location_t();
                    }
                  }
              }).error(function(error){
        console.log(JSON.stringify(error));
        self.setContact_t();
    });
},

Upvotes: 1

Views: 220

Answers (1)

georgeawg
georgeawg

Reputation: 48968

The general answer to your question is return promises and chain from them.

self.setContact_t = function() {
    //save httpPromise for chaining
    var p1 = $http.get(ApiEndpoint.url+'/contacts')
          .then(function(response) {
                console.log(JSON.stringify(response.data));
                return response.data;
        }).catch(function(error){
                console.log(JSON.stringify(error.data));
                //don't recursively call self on error
                //self.setContact_t();
                throw error;
        });
    //chain from httpPromise
    var p2 = p1.then ( function (dataList) {
        var p = $q.when();
        //iterate dataList items
        angular.forEach(dataList, function(data) {
            if (data.insert_date == null) {
                data.insert_date = "0000-00-00 00:00:00";
            };
            //chain items
            p = p.then( function () {
                        console.log("inserting in setContact_t");
                        return $cordovaSQLite.execute(db, insert(data));
            });
        };
        //return promise for chaining
        return p;
    });
    //chain again for setApmLocation
    var p3 = p2.then ( function () {
                         return self.setApm_location_t();
    });      
   //return promise for further chaining
   return p3;
};

Notice the use of the .then and .catch methods and that they return data differently then .success and .error.

Upvotes: 2

Related Questions