【问题标题】:return an object from a function that was put together my promises in that function从函数中返回一个对象,该函数将我的承诺放在该函数中
【发布时间】:2016-12-13 02:01:40
【问题描述】:

我使用 Promise 创建了一个对象,但我无法返回该对象。 console.log("pageStuff inside ", pageStuff) 控制所需的对象,但我不知道如何从 pageStuff 函数返回它。

function pageStuff(incoming){
    //pass in comp1
    var pageStuff = {}
    Reviews.find({companyName : incoming, vote : "down"}).count().exec()
    .then(function(returnedDown){
        pageStuff.downVotes = returnedDown;
    })
    .then(function(){
         return Reviews.find({companyName : incoming, vote : "up"}).count().exec()
    })
    .then(function(returnedUp){
        pageStuff.upVotes = returnedUp;
    })
    .then(function(){
        return Reviews.find({companyName : incoming}).count().exec();
    })
    .then(function(totalReviews){
        pageStuff.totalReviews = totalReviews
        pageStuff.voteResult = pageStuff.upVotes - pageStuff.downVotes;
        if(pageStuff.voteResult > 0){
            pageStuff.voteResult = "+" + pageStuff.voteResult;
        }

    }) 

    .then(function(){
        Reviews.aggregate([
            {$match : {companyName : incoming } },
            {$unwind : "$statements"},
            {$group : {
                _id : "$statements.question",
                result : {$avg  : "$statements.result"}
            }}
        ]).exec(function(err, doc){
            if(err) throw err;
            doc.forEach(function(e){
                e.result = Math.round(e.result * 10) /10
            })
            // console.log("doc: "  , Array.isArray(doc) )
            pageStuff.statements = doc;
            console.log("pageStuff inside ", pageStuff)

        })

    })       
     .catch(function(err){
        console.log(err)
    })  

    return pageStuff;        

}

使用它会给我一个空的{}

我感觉这是一个异步问题,但我不知道如何解决它。

console.log("pagestuff :::: ", pageStuff("comp1"))

【问题讨论】:

  • 在同名函数中使用 var 并不是一个好主意(pageStuff),除此之外,您的函数会在任何异步函数真正开始之前同步返回一个值,更不用说结束了 - 所以,你是对的,这是一个异步的东西,而且由于 Promises 不会使异步代码同步,你需要重新考虑你在做什么,停止尝试将 asynch 变为 synch,因为你不能这样做
  • 只需在Reviews.find 之前添加一个return - 然后您的代码将返回一个promise,当您调用您的函数时,使用.then 就像您对任何promise 一样 - 但是,您需要重写您的函数一点点成功返回你需要的值
  • 我按照您所说的将return 放入我的代码中应该更改的部分。 pageStuff("comp1") .then(function(returnedData){ console.log("returnedData " , returnedData) }) 给我未定义
  • 可能会在 Review.aggregate 前面返回 - 很奇怪,在编写的函数中使用 Promise 似乎很自在,但您很难从该函数返回所需的 Promise

标签: javascript node.js object mongoose promise


【解决方案1】:

Promise 是异步的,return 用于同步值。

一些可能性:

  • 不要返回您感兴趣的值。而是返回 Promise。调用者可以在.then() 中按照它返回的承诺做他们需要做的事情。

  • 例如,如果这是一个库,您不想将 Promise 泄露给正在使用它的东西,那么仍然不要返回该值。相反,当您拥有数据并将数据作为参数发送到事件处理程序时,在 then() 子句中发出一个事件。库用户应为发出事件的对象添加事件处理程序并处理处理程序内的数据。

【讨论】:

    【解决方案2】:

    我这样做是为了让整个函数返回一个承诺。然后

    然后我调用了返回承诺的函数 我得到了结果。谢谢你们的帮助。

    pageStuff("comp1") .then(function(returnedData){ console.log("returnedData " , returnedData) })

    function pageStuff(incoming){
        //pass in comp1
        var returnPageStuff = {}
       return  Reviews.find({companyName : incoming, vote : "down"}).count().exec()
        .then(function(returnedDown){
            returnPageStuff.downVotes = returnedDown;
        })
        .then(function(){
             return Reviews.find({companyName : incoming, vote : "up"}).count().exec()
        })
        .then(function(returnedUp){
            returnPageStuff.upVotes = returnedUp;
        })
        .then(function(){
            return Reviews.find({companyName : incoming}).count().exec();
        })
        .then(function(totalReviews){
            returnPageStuff.totalReviews = totalReviews
            returnPageStuff.voteResult = returnPageStuff.upVotes - returnPageStuff.downVotes;
            if(returnPageStuff.voteResult > 0){
                returnPageStuff.voteResult = "+" + returnPageStuff.voteResult;
            }
    
        }) 
    
        .then(function(){
            Reviews.aggregate([
                {$match : {companyName : incoming } },
                {$unwind : "$statements"},
                {$group : {
                    _id : "$statements.question",
                    result : {$avg  : "$statements.result"}
                }}
            ]).exec(function(err, doc){
                if(err) throw err;
                doc.forEach(function(e){
                    e.result = Math.round(e.result * 10) /10
                })
                // console.log("doc: "  , Array.isArray(doc) )
                returnPageStuff.statements = doc;
                console.log("returnPageStuff inside ", returnPageStuff)
    
            })
           .then(function(){
                 return returnPageStuff
             })    
        })      
    
         .catch(function(err){
            console.log(err)
        })  
    
    
    }
    pageStuff("comp1")
        .then(function(returnedData){
            console.log("returnedData " , returnedData)
        }) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2017-05-30
      • 2018-09-26
      • 2020-07-05
      相关资源
      最近更新 更多