[英]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.