我有以下代码:
app.get('/autocompleteEmployees', function(req, res){
var term = req.param('term');
model.Employee.findAll().success(function(employees){
var responseData = [];
for(var i=0; i<employees.length; i++){
console.log('i: ' + i);
model.Person.find(employees[i].personID).success(function(person){
if((person.lastName + ', ' + person.firstName).toLower().indexOf(term.toLower()) > -1){
responseData.push({
label: person.lastName + ', ' + person.firstName,
value: employees[i].id
});
}
if(i + 1 == employees.length){
res.send(JSON.stringify(repsonseData));
}
});
}
});
});
一旦调用了GET / autocompleteEmployees路由,我就会收到以下错误:
C:\Users\lowerkey\Desktop\emasc\server\controllers\Employee.js:85
model.Person.find(employees[i].personID).success (function(person){
^ TypeError: Object [object Object] has no method 'success'
at [object Object].<anonymous> (C:\Users\lowerkey\Desktop\emasc\server\contr ollers\Employee.js:85:46)
at [object Object].emit (events.js:67:17)
at [object Object].<anonymous> (C:\Users\lowerkey\Desktop\emasc\node_modules \sequelize\lib\query-interface.js:245:17)
at [object Object].emit (events.js:88:20)
at [object Object].<anonymous> (C:\Users\lowerkey\Desktop\emasc\node_modules \sequelize\lib\dialects\mysql\query.js:78:10)
at C:\Users\lowerkey\Desktop\emasc\node_modules\sequelize\lib\dialects\mysql \query.js:32:51
at Query.<anonymous> (C:\Users\lowerkey\Desktop\emasc\node_modules\sequelize \node_modules\mysql\lib\client.js:108:11)
at Query.emit (events.js:64:17)
at Query._handlePacket (C:\Users\lowerkey\Desktop\emasc\node_modules\sequeli ze\node_modules\mysql\lib\query.js:51:14)
at Client._handlePacket (C:\Users\lowerkey\Desktop\emasc\node_modules\sequel ize\node_modules\mysql\lib\client.js:312:14)
我该怎么做才能摆脱错误?
答案 0 :(得分:0)
事实证明,人们不会简单地将for循环与异步代码混合在一起。
对于那些和我一样走路的人来说,解决办法是这样的:
Array.prototype.foreach = function( callback ) {
for( var k=0; k<this .length; k++ ) {
callback( k, this[ k ] );
}
}
app.get('/autocompletePersonEmployees', function(req, res){
console.log('/autocompleteEmployees');
var term = req.param('term', null);
if(term == null){
model.Employee.findAll().success(function(employees){
var responseData = [];
employees.foreach(function(i, employee){
console.log(i + ' ' + employee.toString());
model.Person.find(employee.personID).success(function(person){
responseData.push({
label: person.lastName + ', ' + person.firstName,
value: employee.id
});
if(i+1 == employees.length){
res.send(JSON.stringify(responseData));
}
});
});
});
}
});
答案 1 :(得分:0)
您可能会发现使用热门async库中的forEach调用更容易,而不是自己定义。