Promises和nodejs的具体例子(也没有解决scheme)

因此,我想通过尝试使用nodejs来实现一个常见用例,来了解有关Promises的更多信息(我任意select了Bluebird,尽pipe“简洁”文档):

我有一堆9000左右的URL在一个文件中,也有一些空行。 我想要:

  • 过滤空行(url.length <= 0)
  • 筛选出不再响应的请求(通过使用request模块的HEAD请求)
  • MAP通过dns.resolve()获取IPv4地址
  • MAP使用IPv4地址和http://ipinfo.io/xx.xx.xx.xx/geo来获取地理数据(好的,是的,每天都有API限制,但是我们假设我可以)
  • 将结果信息作为JSON对象数组写入新文件
  • 当然,这是可以并行运行的,因此比按顺序运行要快得多

第一个filter很容易,因为它立即返回(这里使用蓝鸟):

 Promise.each(urls, function(value, index, length) { return value.length > 0; }).then( console.log(urls); ); 

但是我怎样才能将asynchronous头请求的结果反馈给Promise呢? 这里是另一个更完整的例子,我打了一堵墙(见内联评论):

 <pre class="prettyprint lang-js"> var Promise = require('bluebird'), request = Promise.promisifyAll(require('request')); var urls = ["", "https://google.com/", "http://www.nonexistent.url"]; var checkLength = function(url) { return Promise.resolve(url.length > 0); } var checkHead = function(url) { return Promise.resolve( // ??? seee below for an 'unPromised' function that works on its own ) } var logit = function(value) { console.log((urls.length - value.length) + " empty line(s)"); } Promise .filter(urls, checkLength) // and here? .filter(urls, checkHead) ? I don't think this would work. // and I haven't even look at the map functions yet, although I guess // that once I've understood the basic filter, map should be similar. .then(logit); </pre> 

对于checkHead函数,我打算修改这样的东西:

 var isURLvalid = function(url) { request .head(url) .on('response', function(response) { console.log("GOT SUCCESS: " + response); callback(response.statusCode < 300); }) .on('error', function(error) { console.log("GOT ERROR: " + response); callback(false); }) }; 

不想抱怨,我仍然拼命寻找一些很好的教程介绍资料,让那些不熟悉Promise的开发者展示一些常见用例的实际实现,像cookbook一样。 如果有的话,我很乐意得到一些指示。

filter和贴图函数的工作方式与JavaScript Array的默认方式相同。

我之前使用过承诺请求,并且有一个特定的模块用于这个叫做request-promise。 这可能会更方便。

我觉得请求承诺模块很好地展示Promise是如何伟大的。

而不是陷入callback地狱,每增加一个请求就会变得更深,你可以用承诺去做

 rp(login) .then(function(body) { return rp(profile); }) .then(function(body) { return rp(profile_settings); }) .then(function(body) { return rp(logout); }) .catch(function(err) { // the procedure failed console.error(err); }); 

我重写了你的当前代码

 var Promise = require("bluebird"); var rp = require("request-promise"); var urls = ["", "https://google.com/", "http://www.nonexistent.url"]; Promise // checkLength .filter(urls, function(url){return url.length > 0}) .then(function(list) { // logit console.log((urls.length - list.length) + " empty line(s)"); // checkHead return Promise.filter(list, function(url) { // using request-promise and getting full response return rp.head({ uri: url, resolveWithFullResponse: true }) .promise().then(function(response) { // only statusCode 200 is ok return response.statusCode === 200; }) .catch(function(){ // all other statuscodes incl. the // errorcodes are considered invalid return false; }); }) }) .then(console.log);