[英]AngularJS and async calls
I'm an AngularJS promises novice and getting really frustrated on how to implement it. 我是AngularJS的新手,对如何实现它感到非常沮丧。 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. ...和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. 当我检查我的日志,我看到
console.log("tempctr out")
被称为第一之前console.log("dlpromise in")
我得到它的,因为这个过程是异步的。 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()
. 这就是为什么我使用
q.all
(基于此SO答案 )的原因,因为我认为在进入then()
之前先解析dlPromise
。 But it didn't work. 但这没有用。 What am I missing?
我想念什么? Is my understanding of AngularJS' promises skewed in general?
我对AngularJS的承诺的理解是否总体上存在偏差?
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");
更新:我在
console.log("dlpromise in");
之后添加了console.log console.log("dlpromise in");
. 。 This is the result:
结果如下:
dlpromise in
[ { _id: 58c7b885db0afd48ee427a73,
employeeID: '12349876',
employeeName: 'Tester'}]
I'm not really familiar with the server-side code, but I'm assuming it's NodeJS? 我不太熟悉服务器端代码,但是我假设它是NodeJS?
I think you could change the code to something in the lines of this (assuming res.json(tempCtr) sends the response data): 我认为您可以将代码更改为以下内容(假设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.