Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active February 5, 2017 01:05
Show Gist options
  • Save joepie91/9593551b41f568a75b08 to your computer and use it in GitHub Desktop.
Save joepie91/9593551b41f568a75b08 to your computer and use it in GitHub Desktop.
Error-tolerant promise map with more bookkeeping (Bluebird)
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. */
});
@vicatcu
Copy link

vicatcu commented Jan 14, 2016

Line 15 shouldn't have a semi-colon at the end.

@joepie91
Copy link
Author

joepie91 commented Feb 5, 2017

@vicatcu Thanks, fixed :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment