簡體   English   中英

如何從響應結果中使用http / https形成對象並將其推入數組

[英]how to form an object and push it into an array using http/https from the resultant of response

我是nodejs的新手,我試圖通過使用“ http.get”形成一個數組,這些數組具有無效的imageUrls,我從mongodb集合中查詢我的產品,盡管我使用的是“ Promise”,該數組首先打印,我沒有從“ hh.get”得到結果

這是我在服務器端的代碼

    var Promise = require('bluebird'),
         hh = require('http-https')
         mongoose = require('mongoose'),
         collection = mongoose.model('Collection');


    function getInValidImgUrl(prodObj){
     return hh.get(prodObj.imageUrl,function(res){
         if(res.statusCode == 404){
            return {
                    name:prodObj.name,
                    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++){
           imgArr.push(getInValidImgUrl(products(i)));
        }

       Promise.all(imgArr).then(results =>{
          console.log("IAMGE ARRAY :"+JSON.stringify(results)); //here iam not getting array
        })

      }
    });
    }

提前致謝。

盡管您可以使用npm包request-promise( https://www.npmjs.com/package/request-promise ),但您實際上並不需要使用bluebird,但我經常使用它。 為了不更改太多內容,您的問題是您要在getInValidImgUrl函數的回調中返回。 您可以更改它以使用隨節點免費提供的標准Promise類( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

function getInValidImgUrl(prodObj){
     return new Promise((resolve,reject) => {
         hh.get(prodObj.imageUrl,function(res){
         if(res.statusCode == 404){
            resolve( {
                    name:prodObj.name,
                    imgUrl:prodObj.imageUrl 
                   })
          }
      })
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM