Dee J.
Dee J.

Reputation: 363

AngularJS and async calls

I'm an AngularJS promises novice and getting really frustrated on how to implement it. I'm hoping somebody here can help me out.

I have the following client-side code:

// Pass result to ng-csv directive.
$scope.generateEmployeeData = function () {
        $scope.employeename = empName;
        $http.get('/api/employee-information/download').then(function (data) {
            console.log(data);
            return data;
        }).catch(function (err) {
            ToastFactory.error({
                title: "Oops!",
                text: "Something went wrong while downloading employee data.",
                icon: "exclamation-sign"
            });
        });
    }

... and the ff. server-side code:

// Download Employee data (.../api/employee-information/download)
exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    var dlPromise = EmployeeInfo.find({}, function (err, results) {
        var tempCtr = [];
        if (err) { return err; }

        console.log("dlpromise in");
        return results;
    });

    q.all(dlPromise)
        .then(function (results) {
            _.forEach(results, function (item) {
                tempCtr.push({
                    employeeID: item.employeeID,
                    employeeName: item.employeeName
                });
            });
        });

    console.log("tempctr out");
    console.log(tempCtr);

    return res.json(tempCtr);
}

When I checked my logs, I saw that console.log("tempctr out") was called first before console.log("dlpromise in"), and I get that it's because the process is asynchronous. That's why I used q.all (based on this SO answer), because I thought that it would resolve dlPromise first before going inside then(). But it didn't work. What am I missing? Is my understanding of AngularJS' promises skewed in general?

I've been trying to solve this for a long time without any success. Please help.

Thank you.

UPDATE: I added a console.log after console.log("dlpromise in");. This is the result:

dlpromise in
[ { _id: 58c7b885db0afd48ee427a73,
    employeeID: '12349876',
    employeeName: 'Tester'}]

Upvotes: 0

Views: 58

Answers (1)

Arg0n
Arg0n

Reputation: 8423

I'm not really familiar with the server-side code, but I'm assuming it's NodeJS?

I think you could change the code to something in the lines of this (assuming res.json(tempCtr) sends the response data):

exports.downloadEmployee = function (req, res) {
    EmployeeInfo.find({}, function (err, results) {
        var tempCtr = [];
        if (err) { return err; }

        _.forEach(results, function (item) {
            tempCtr.push({
                employeeID: item.employeeID,
                employeeName: item.employeeName
            });
        });

        console.log("tempctr out");
        console.log(tempCtr);
        res.json(tempCtr);
    });
}

Upvotes: 1

Related Questions