2016-12-30 140 views
1

我嘗試使用異步庫的NodeJS執行收集API的信息,但async.parallel回調收集,我需要異步回調的NodeJS

這所有的數據之前執行自身後快遞渲染是代碼:

  LolApi.getMatchHistory(app_dtb.summoner.id, "euw", function(err, history) { 
      if (!err) { 
       async.parallel([ 
        function(callback) { 
         LolApi.getMatch(history.matches[nbMatch].matchId, function(err, match) { 
          if (!err) { 
           var teamIn; 

           function getParticipantNb() { 
            for (var i = 0; i < match.participantIdentities.length; i++) { 
             if (app_dtb.summoner.id == match.participantIdentities[i].player.summonerId) { 
              if (i <= 5) teamIn = 100 
              else teamIn = 200 
              return i + 1 
             } 
            } 
            return false; 
           } 

           var participantNb = getParticipantNb() 
           if (match.teams[0].winner == true && teamIn == 100) { 
            app_dtb.lastGame.won = "Win"; 
           } else { 
            app_dtb.lastGame.won = "Loose"; 
           } 
           console.log(app_dtb.lastGame.won) 
          } else { 
           console.log(err) 
          } 

         }); 
         setTimeout(function() { 
          callback(null, "one"); 
         }, 200); 
        }, 
        function(callback) { 
         options = { 
          champData: 'allytips,blurb', 
          version: '4.4.3', 
          locale: 'en_US' 
         } 
         LolApi.Static.getChampionById(history.matches[nbMatch].champion, options, function(err, champ) { 
          if (!err) { 
           console.log(champ.name); 
           app_dtb.lastGame.champName = champ.name 

          } else { 
           console.log(err) 
          } 

         }); 
         setTimeout(function() { 
          callback(null, "two"); 
         }, 100); 
        } 
       ], function(err, results) { 
        console.log(results) 
        res.render("index"); 
       }); 
      } else { 
       console.log(err); 
      } 

     }) 

任何想法或其他方式有相同的結果?

非常感謝

+1

你的代碼有什麼問題或者你正試圖解決的問題? –

+0

我試圖呈現索引後的一系列console.log記錄我需要的一切,但目前索引呈現本身在日誌結束之前 –

回答

0

你應該打電話給你LolApi回調方法裏面的callback和酸酸的async回調最終將要求兩個平行的功能。因此可能在LolApi回調之前呼叫timeout

+0

這似乎工作,而且我刪除了超時(我不知道是否有效果)謝謝! –