Async Await返回Promise <pending>

时间:2017-09-15 21:18:10

标签: javascript node.js asynchronous

我正在尝试在快速路由中使用async / await,并且无法使其正常工作。我看了几篇SO帖子,看来我做得对。

助手:

module.exports = {

 facebook: function(userId, token) {
   return new Promise(resolver)
   function resolver(resolve, reject) {
      graph.get(`${userId}/feed?access_token=${token}`, function(err, res) {
         if (err) {
            if(res.paging && res.paging.next) {
              graph.get(res.paging.next, function(err2, res2) {

                var arr = []

                res.data.forEach(function(e) {
                  if (e.hasOwnProperty('message')) {
                    arr.push(e.message) 
                  } else if (e.hasOwnProperty('story')) {
                    arr.push(e.story)
                  } else {
                    console.log('something is not here')
                  }
                }) 

                res2.data.forEach(function(e) {
                  if (e.hasOwnProperty('message')) {
                  arr.push(e.message) 
                  } else if (e.hasOwnProperty('story')) {
                    arr.push(e.story)
                  } else {
                    console.log('something is not here')
                  }
                })
                console.log(arr)
                resolve(arr.toString())

              })

            }
         } 
      })
   }      

  },
  twitter: function(twittername) {
    return new Promise(resolver) 
    function resolver(resolve, reject) {
      T.get('search/tweets', { q: `from:${twittername}`, count: 500 }, function(err, data, response) {
        if (err) {
          reject(err)
          console.log(err)
        } else {
          data.statuses.forEach(function(e) {
          arr.push(e.text)
        })

      }
      resolve(arr.toString())
    })

    }

    console.log(arr)
     return arr.toString()
},
personalityInsights: function (fullString) { 
  console.log('fullString', fullString)
  personality_insights.profile({
      text: fullString,
      consumption_preferences: true
    },
    function (err, response) {
      if (err) {console.log(err)}
      else console.log(response)
    });
  }
}

在Route.js内部

 async function main() {
    try {
       facebookR = await helpers.facebook(userId, accessToken)
       twitterR = await helpers.twitter(twittername)
       return await helpers.personalityInsights(`${facebookR} ${twitterR}`)
    } catch (e) {
      console.log('err main', e)
    }
  }

 main()

我最初在帮助程序中使用回调并将它们转换为promises时遇到了问题,因为我学习了异步函数返回promises。但是使用这段代码,我仍然无法返回我想要的值。我做错了什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

personalityInsights: function (fullString) { 
  console.log('fullString', fullString)
  personality_insights.profile({
      text: fullString,
      consumption_preferences: true
    },
    function (err, response) {
      if (err) {console.log(err)}
      else console.log(response)
    });
  }

您应该从personalityInsights函数返回一些值。