javascript - Node.js Async Promises within a forEach Loop inside another then statement -
i have been trying understand promises nesting simple code.
both functions i'm calling async, 1 giving entire collection , other individual information of each of elements.
what doing wrong?
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 = []; (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); });
you don't need async module, promise
should sufficient. in particular might interested in promise.all()
takes array of promises , resolves when promises finishes. using array.prototype.map()
each element of ltorrents
can mapped promise. here's example..
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 1 request fails, whole promise.all() rejects, // can catch ones fail , instead... t.doc = "unavailable (because gettorrent failed)"; return t; }); })); }) .then(function(ltorrents) { // gota do.. })
Comments
Post a Comment