簡體   English   中英

Async Await返回Promise <pending>

[英]Async Await Returns Promise <pending>

我試圖在快速路由中使用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。 但是使用這段代碼,我仍然無法返回我想要的值。 我做錯了什么,我該如何解決?

 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函數返回一些值。

暫無
暫無

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

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