【发布时间】:2015-01-23 15:09:51
【问题描述】:
目前我正在使用 Promise 来尝试防止在我的代码中需要嵌套回调,但我遇到了挫折。在这种情况下,我使用节点的 request-promise 和cheerio 在服务器上模拟 jQuery。但是,有时我需要调用jQuery.each(),为每个<a> 元素创建一个请求。有什么方法可以使用 Promise 来防止这种嵌套回调?
request("http://url.com").then(function (html) {
var $ = cheerio.load(html);
var rows = $("tr.class a");
rows.each(function (index, el) {
//Iterate over all <a> elements, and send a request for each one.
//Can this code be modified to return a promise?
//Is there another way to prevent this from being nested?
request($(el).attr("href")).then(function (html) {
var $ = cheerio.load(html);
var url = $("td>img").attr("src");
return request(url);
})
.then(function (img) {
//Save the image to the database
});
});
});
【问题讨论】:
标签: javascript jquery node.js promise cheerio