繁体   English   中英

AngularJS和异步调用

[英]AngularJS and async calls

我是AngularJS的新手,对如何实现它感到非常沮丧。 我希望这里有人可以帮助我。

我有以下客户端代码:

// 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"
            });
        });
    }

...和ff。 服务器端代码:

// 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);
}

当我检查我的日志,我看到console.log("tempctr out")被称为第一之前console.log("dlpromise in")我得到它的,因为这个过程是异步的。 这就是为什么我使用q.all (基于此SO答案 )的原因,因为我认为在进入then()之前先解析dlPromise 但这没有用。 我想念什么? 我对AngularJS的承诺的理解是否总体上存在偏差?

我一直在努力解决这一问题,但没有成功。 请帮忙。

谢谢。

更新:我在console.log("dlpromise in");之后添加了console.log console.log("dlpromise in"); 结果如下:

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

我不太熟悉服务器端代码,但是我假设它是NodeJS?

我认为您可以将代码更改为以下内容(假设res.json(tempCtr)发送响应数据):

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);
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM