Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to insert promises during chain execution using node.js Q?
    text
    copied!<p>I have a promise chain that requests an RSS URL, parses it for links, then needs to request each link. The first part works great. However I'm having trouble working out how to "insert the promises" that request each link that has been parsed.</p> <p>I started by generating a simple array of link URLs (preferred method) but couldn't make that work. The code now generates an array of promises to request each URL but I don't know how to make that work either. Perhaps I need to use <a href="https://github.com/kriskowal/q/wiki/API-Reference" rel="nofollow" title="Q API">Q.all()</a> but that seems to be for predetermined functions?</p> <pre><code>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 = /&lt;link&gt;([^&lt;$]+)/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; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload