-
-
Save joepie91/9593551b41f568a75b08 to your computer and use it in GitHub Desktop.
Error-tolerant promise map with more bookkeeping (Bluebird)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var bhttp = require("bhttp"); | |
var urls = [ | |
"http://google.com/", | |
"http://yahoo.com/", | |
"http://bing.com/" // Ha ha, just kidding who uses Bing anyway :) | |
]; | |
Promise.try(function(){ | |
/* There's a faster shorthand for this, but for illustrative purposes, we'll just return the array here and pretend that it was generated by something else, somehow. */ | |
return urls; | |
}).map(function(url){ | |
/* Turn it into an object... */ | |
return { | |
url: url | |
}; | |
}).map(function(task){ | |
return Promise.try(function(){ | |
return bhttp.get(task.url); | |
}).catch(function(err){ | |
return null; | |
}).then(function(response){ | |
task.response = response; | |
return task; | |
}) | |
}).filter(function(task){ | |
return (task.response != null); | |
}).map(function(task){ | |
task.body = task.response.body; | |
return task; | |
}).then(function(tasks){ | |
/* Now `tasks` is an array of tasks, one for each successful URL, and with a `body` property containing the response body. */ | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 15 shouldn't have a semi-colon at the end.