1

I have one function, I am required to print the lastlockerbalance outside the function.

var getlockerbalance = function() {
    $http.get("php/selectLOCKERBALANCE.php").success(function(lockerbalance) {
        $scope.lockerbalance1 = lockerbalance;
        var lastlockerbalance = $scope.lockerbalance1[0].LOCKERBALANCE;
        console.log(lastlockerbalance);
    });
};
console.log(lastlockerbalance);

Showing error message as "lastlockerbalance is undefined".

2 Answers 2

2

You can't. The .success() callback won't even have been called by the time your second console.log() function is called, in fact the request $http.get() call won't even send the request until after the getlockerbalance() function returns.

What you need to do is move the code that uses the value inside the callback.

Sign up to request clarification or add additional context in comments.

1 Comment

I do agree with you, but (window).lastlockerbalance will be set (not at the time the OP is printing it). Of course, it should be moved inside a callback.
0

You could either return a promise and use then() or pass a callback to the function.

Promise

function getlockerbalance() {
     return $http.get("php/selectLOCKERBALANCE.php").success(function(lockerbalance) {
        $scope.lockerbalance1 = lockerbalance;
        var lastlockerbalance = $scope.lockerbalance1[0].LOCKERBALANCE;
        return lastlockerbalance;
    });
};

getlockerbalance().then(function(result){
    console.log(result);
});

Callback

var getlockerbalance = function(callback) {
    $http.get("php/selectLOCKERBALANCE.php").success(function(lockerbalance) {
        $scope.lockerbalance1 = lockerbalance;
        var lastlockerbalance = $scope.lockerbalance1[0].LOCKERBALANCE;
        callback(lastlockerbalance);
    });
};

function printBalance(balance) {
    console.log(balance);
}

getlockerbalance(printBalance);

2 Comments

Your promise example needs to assign to lastlockerbalance in the outer scope: lastlockerbalance = getlockerbalance() though it might be better to give it a different name to distinguish the promise from the value.
yeah, I refactored. but he should get the idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.