我有一个请求 RSS URL 的 promise 链,解析它以获取链接,然后需要请求每个链接。第一部分效果很好。但是,我无法弄清楚如何“插入 promise ”来请求已解析的每个链接。
我首先生成一个简单的链接 URL 数组(首选方法),但无法实现。该代码现在生成一组请求每个 URL 的 promise ,但我也不知道如何让它工作。也许我需要使用 Q.all()但这似乎是为了预定的功能?
requestRss(rssSourceUrl)
.then(function(links) {
// ???
})
.catch(function(error) {
console.log(error);
})
.done();
function requestRss(url) {
var deferred = q.defer();
request(url, function(err, resp, body) {
if (err || resp.statusCode !== 200) {
deferred.reject(new Error(resp.statusCode + ' ' + err + ' ' + body));
} else {
$ = cheerio.load(body);
var linkRegex = /<link>([^<$]+)/gim;
var someLinks = new Array();
$('item').each(function() {
var match = linkRegex.exec($(this).html());
if (match) {
var link = match[1];
someLinks.push(
function() { requestSomeLink(link); }
);
}
});
deferred.resolve(someLinks);
}
});
return deferred.promise;
}
function requestSomeLink(url) {
var deferred = q.defer();
request(url, function(err, resp, body) {
if (err || resp.statusCode !== 200) {
deferred.reject(new Error(resp.statusCode + ' ' + err + ' ' + body));
} else {
$ = cheerio.load(body);
deferred.resolve(body);
}
});
return deferred.promise;
}
最佳答案
The code now generates an array of promises to request each URL
实际上它是一个函数数组,每个函数在调用时都会产生一个 url 请求的 promise 。我认为你应该简单地把它做成一个链接(字符串)数组,仅此而已 - 它们会发生什么是在另一个函数中确定的。所以
function requestLinksFromRss(url) {
…
if (match)
someLinks.push(match[1]);
…
return deferred.promise;
}
Perhaps I need to use Q.all() but that seems to be for predetermined functions?
我不明白你所说的“预定功能”是什么意思。 Q.all()
只是将一系列 promise 作为其论点。这就是我们所拥有的。
requestLinksFromRss(rssSourceUrl).then(function(links) {
var promiseArr = links.map(requestSomeLink); // or a loop if you want
return Q.all(promiseArr);
}).then(function(ressources) {
// now you have an array of request bodies.
// Do something with them.
}).catch(console.log.bind(console)).done();
关于javascript - 如何使用 node.js Q 在链执行期间插入 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733909/