![](/img/trans.png)
[英]Node.js Promises within promises not waiting for for loop to return data
[英]Node.js Async Promises within a forEach Loop inside another then statement
我一直在尝试理解使用此简单代码嵌套的Promise。
我要调用的两个函数都是异步的,一个函数提供了整个集合,另一个函数只是每个元素的单独信息。
我究竟做错了什么?
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);
});
您不需要异步模块, Promise
应该足够了。 特别是您可能感兴趣的是Promise.all()
,它接受一个Promises数组,并在所有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..
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.