【问题标题】:Promise is not working while forming an arrayPromise 在形成数组时不起作用
【发布时间】: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 的其余所有产品
  • 200202 不同,是吗?

标签: javascript angularjs arrays node.js express


【解决方案1】:

getInValidImgUrl是异步的,你的imgArr在返回结果后的回调中填写。

您的 promise.all 在所有先前的 http 请求承诺返回之前被执行。

查看here for Promise.all docs

试试:

var calback=[];
 for(var i=0; i<products.length: i++){
           calback[i] = getInValidImgUrl(products(i));
        }
 Promise.all(calback).then(results =>{
          console.log("IAMGE ARRAY :"+JSON.stringify(results)); 
        })

A sample js fiddle to show Promise.all

【讨论】:

  • 我只在该数组中获得一个剩余的对象并没有推入该数组@Suraj Rao
  • 在 Promise.all 中添加一个 catch 并检查是否有任何错误
  • iam 没有收到任何错误,我说的是在将值从getInValidImgUrlfunction 分配给calback[i] 的过程中,它只将一个值推送到数组中,因此它只打印一个对象@Suraj Rao
  • 所有状态都很好,我将Promise.all 更改为Promise.each 是否甚至一个对象正在打印(或)不打印,当我使用Promise.all 控制台时它显示一个对象不是打印@Suraj Rao
  • 可能不相关但on('error', function (e) { // console.error(e); resolve({ type: 'error', ImgUrl: prodObj.imageUrl }) })应该被拒绝...
猜你喜欢
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 2016-08-03
  • 2017-11-17
  • 2021-10-28
  • 1970-01-01
相关资源
最近更新 更多