Belal Othman Belal Othman - 4 months ago 8
Javascript Question

I need to call a function when previous function has finished

I am using angularJs and I use this function in my controller to get data from database

this.callServer = function callServer(criteria) {
ctrl.searchParameters = criteria;
ctrl.isLoading = true;
var start = $scope.itemsPerPage * ($scope.currentPage - 1);
var limit = $scope.itemsPerPage;
service.getRandomsItems(criteria, start, limit).then(
function(result) {
var remainder = $scope.totalItems % $scope.itemsPerPage
if (remainder > 0)
$scope.numPages = parseInt($scope.totalItems / $scope.itemsPerPage) + 1;
else
$scope.numPages = parseInt($scope.totalItems / $scope.itemsPerPage);

ctrl.displayed = result.randomsItems;
$scope.totalItems = result.total;
ctrl.isLoading = false;
});
};
}


and I call this function in my controller too to handle the paging issue

$scope.pageChanged = function(currentPage) {
$scope.currentPage = currentPage;
ctrl.callServer($scope.criteria);
}


As you can see, my function callServer returns ctrl.displayed which is the rows that displayed in current page

Now I want to work with new page so I called ctrl.callServer to get new page then I called ctrl.selectCurrentPage() just like that

$scope.pageChanged = function(currentPage) {
$scope.currentPage = currentPage;
ctrl.callServer($scope.criteria);
ctrl.selectCurrentPage() // I want this function to be called when ctrl.callServer($scope.criteria) is finished
}


where

ctrl.selectCurrentPage = function() {
ctrl.selection.push(this.displayed[i].userId);
ctrl.selectionRow.push(this.displayed[i]);
}


in Simple English I want ctrl.selectCurrentPage to be called when ctrl.callServer is finsih and get the new data
but that not happen.

Answer

Just return a promise from callServer and use it in pageChanged.

The first step:

this.callServer = function callServer(criteria) {
    ctrl.searchParameters = criteria;
    ctrl.isLoading = true;
    var start = $scope.itemsPerPage * ($scope.currentPage - 1);
    var limit = $scope.itemsPerPage;

    return service.getRandomsItems(criteria, start, limit).then(function(result) {
        var remainder = $scope.totalItems % $scope.itemsPerPage
        if (remainder > 0)
            $scope.numPages = parseInt($scope.totalItems / $scope.itemsPerPage) + 1;
        else
            $scope.numPages = parseInt($scope.totalItems / $scope.itemsPerPage);

        ctrl.displayed = result.randomsItems;
        $scope.totalItems = result.total;
        ctrl.isLoading = false;
    });
};

Then:

$scope.pageChanged = function(currentPage) {
    $scope.currentPage = currentPage;
    ctrl.callServer($scope.criteria).then(function () {
        ctrl.selectCurrentPage();
    });
}

Try to avoid callback hell. Please read the article for some useful information.