Javascript 保证不在循环内返回
我有控制器和模型文件。我想将承诺的响应从模型返回给控制器。作为对模型函数conole.logresponse的响应,我给出了结果,但我无法将其发送回控制器函数 我的控制器功能是 在控制器中,请尝试以下操作:Javascript 保证不在循环内返回,javascript,node.js,promise,Javascript,Node.js,Promise,我有控制器和模型文件。我想将承诺的响应从模型返回给控制器。作为对模型函数conole.logresponse的响应,我给出了结果,但我无法将其发送回控制器函数 我的控制器功能是 在控制器中,请尝试以下操作: let filters; for(var i = 0; i < 10; i++){ ModelFile.getResult(i).then(res => { console.log(res); filters = res; }); console.log(filt
let filters;
for(var i = 0; i < 10; i++){
ModelFile.getResult(i).then(res => {
console.log(res);
filters = res;
});
console.log(filters);
}
在控制器中,请尝试以下操作:
let filters;
for(var i = 0; i < 10; i++){
ModelFile.getResult(i).then(res => {
console.log(res);
filters = res;
});
console.log(filters);
}
记住从模型函数的final then返回响应。当我返回响应时,它会在controllerLike@jensgram中给出未定义的返回响应。然后,即使您已经尝试过,我建议您更新您的代码,但您尚未确认外部连接。query。记住从模型函数的final then返回响应模型函数。当我返回响应时,它在controllerLike@jensgram中给出未定义的最终返回响应。然后,即使您已经尝试过,我建议您更新您的代码,您还没有确认外部连接。query.thanking但显示错误无法读取此处未定义的ModelFile.getResulti.thenres=>{ModelFile.getResulti当时不存在。这是您的一个错误,您在初始代码段中提供了这一点。您必须用getProductOptions函数替换ModelFile.getResulti。这是一个错误。我已经更新了,但仍然没有显示。在这种情况下,模型函数没有返回像/thenable那样的承诺。请确保返回connquery…也是。谢谢,但显示错误无法读取此处未定义的ModelFile.getResulti.thenres=>{ModelFile.getResulti当时不存在。这是您的一个错误,您在初始代码段中提供了这一点。您必须用getProductOptions函数替换ModelFile.getResulti。这是一个错误。我已经更新了,但仍然没有显示。在这种情况下,模型函数没有返回像/thenable那样的承诺。请确保返回conn我也是。
getProductOptions = (product_id) => {
connection.query(query1,function(err,rows) {
var response = [];
//doing something with rows
Promise.all(rows.map(function(item) {
var promise = new Promise(function(resolve,reject) {
connection.query(queryItem,function(err,rows) {
//doing something
result = rows[0].field;
//and want to push it to an array
resolve(result);
});
});
return promise.then(function(result) {
console.log(result); //ok
response.push(result) //ok
});
}).then(function () {
return response;
});
});
}
let filters;
for(var i = 0; i < 10; i++){
ModelFile.getResult(i).then(res => {
console.log(res);
filters = res;
});
console.log(filters);
}