2016-08-24 86 views
0

我一直在試圖理解使用這個簡單代碼嵌套的承諾。Node.js在forEach循環內的異步承諾在另一個語句內

我調用的兩個函數都是異步的,一個給出了整個集合,另一個給出了每個元素的單獨信息。

我在做什麼錯?

const PirateBay = require ('thepiratebay'); 
var os = require ('os'); 
var sys = require('util'); 
var util = require('util'); 
var cfg = require('./config/appconf.js'); 
var mysql = require('mysql'); 
var Torrent = require('./models/torrent.js'); 
var parseTorrent = require('parse-torrent') 

var async = require('async'); 
function saveResults (results) { 
    console.log("Save Results"); 
    var cTorrents = []; 
    for (var key in results) { 
     var t =results[key]; 
     var torrent = new Torrent() 
     torrent.id = t.id; 
     torrent.name = t.name; 
     torrent.size = t.size; 
     torrent.seeders = t.seeders; 
     torrent.leechers = t.leechers; 
     torrent.verified = t.verified; 
     torrent.uploader = t.uploader; 
     torrent.category = t.category.name; 
     torrent.description = t.description; 
     torrent.subcategory = t.subcategory.name; 
     var r = parseTorrent (t.magnetLink); 
     torrent.announce = r.announce; 
     torrent.hash = r.infoHash; 
     cTorrents.push (torrent); 
    } 
    return cTorrents; 
} 
PirateBay 
    .recentTorrents() 
    .then(function(results){ 
     var lTorrents = saveResults(results); 

     async.each (lTorrents,function (t,next){ 
       await PirateBay 
        .getTorrent(t.id) 
        .then(function (err, doc){ 
         console.log(doc.description); 
         t.doc = doc.description; 
         next(); 
        }); 
     },function (err) { 
      console.log ("WHNEEEEE"); 
      console.log(lTorrents); 
     }); 
     console.log(lTorrents); 
    }) 
    .catch (function (err){ 
     console.log(err); 
    }); 
+1

你爲什麼認爲有什麼問題?有問題嗎?它是什麼,你期望發生什麼? –

回答

0

您不需要異步模塊,Promise應該足夠了。特別是你可能感興趣的是Promise.all(),它需要一系列的承諾,並在所有承諾完成時解決。使用Array.prototype.map()lTorrents的每個元素都可以映射到Promise中。這裏有一個例子..

PirateBay 
     .recentTorrents() 
     .then(function(results){ 
      var lTorrents = saveResults(results); 
      return Promise.all(lTorrents.map(function(t) { 
       return PirateBay.getTorrent(t.id) 
        .then(function(doc) { 
         t.doc = doc.description; 
         return t; 
        }) 
        .catch(function(err) { 
         // if one request fails, the whole Promise.all() rejects, 
         // so we can catch ones that fail and do something instead... 
         t.doc = "Unavailable (because getTorrent failed)"; 
         return t; 
        }); 
      })); 
     }) 
     .then(function(lTorrents) { 
      // do what you gota do.. 
     })