【发布时间】:2017-05-15 07:51:42
【问题描述】:
我试图在我的服务器端使用“Promise”形成一个结果对象数组,但在将全部对象推送到该数组后该数组未打印,它显示一个空数组
这是我的代码
var Promise = require('bluebird'),
hh = require('http-https')
mongoose = require('mongoose'),
collection = mongoose.model('Collection');
function getInValidImgUrl(prodObj){
return new Promise((resolve, reject) => {
hh.get(prodObj.imageUrl, function (res) {
if (res.statusCode !== 200) {
/* console.log("IN HHHHH : " + res.statusCode);*/
resolve({
type: 'success',
ImgUrl: prodObj.imageUrl
})
}
}).on('error', function (e) {
// console.error(e);
resolve({
type: 'error',
ImgUrl: prodObj.imageUrl
})
});
})
};
exports.sampleFunc=function(){
collection.find({category:"electronics"}).exec(function(err,products){
if(err){
console.log(err)
}else{
var imgArr=[];
//eg:products=[{name:"mobile",imageUrl:"http://somepic.jpg"}]
for(var i=0; i<products.length: i++){
var calback = getInValidImgUrl(products(i));
calback.then(function(result){
imgArr.push(result);
console.log(JSON.stringify(imgArr)); // In this it showing every object is pushing into imgArr
})
}
Promise.all(imgArr).then(results =>{
console.log("IAMGE ARRAY :"+JSON.stringify(results)); //here iam not getting array it is showing an empty array
})
}
});
}
我可以知道我在哪里做错了,为什么它没有打印整个数组。
谢谢你
【问题讨论】:
-
if (res.statusCode !== 200) {}条件的预期结果是什么?如果res.statusCode不等于200,您不想调用resolve()吗? -
我正在尝试获取具有
statusCode!=200的产品,这意味着我想要statusCode 没有202 @guest271314 的其余所有产品 -
200与202不同,是吗?
标签: javascript angularjs arrays node.js express