If I run the code as shown on the README at https://github.com/tj/co-parallel#example (I've removed the .()
at the end of the co function since I'm using co version 4, on node with --harmony
flag), the output is as I'd expect, with the seven 200 messages (status codes) appearing for each of the requests.
GET http://google.com
GET http://yahoo.com
GET http://ign.com
GET http://cloudup.com
GET http://myspace.com
GET http://facebook.com
GET http://segment.io
[ 200, 200, 200, 200, 200, 200, 200 ]
I'm trying to understand how error handling works. If I change the demo in the README to throw Errors (first 3 lines under status
function) and add an error handler to the main co function (last 3 lines below), I get some behaviour I don't understand as I'm new to generators and asychronous.
function *status(url) {
if (url.contains('yahoo')) {
throw Error('my error');
}
console.log('GET %s', url);
return (yield request(url)).statusCode;
}
...
co(function *(){
var reqs = urls.map(status);
var res = yield parallel(reqs, 2);
console.log(res);
}).catch(function(e) {
console.log(e);
});
If I run it with the above code, the output becomes the following. Instead of yahoo.com appearing I get the error message in its place, which makes sense. But I don't get the final array of any 200 messages appearing.
GET http://google.com
[Error: my error]
GET http://ign.com
GET http://cloudup.com
GET http://myspace.com
GET http://facebook.com
GET http://segment.io
And if I add another url to the error condition, changing it to if (url.contains('yahoo') || url.contains('cloudup')) {
the output becomes this:
GET http://google.com
[Error: my error]
GET http://ign.com
Here the yahoo.com line is still replaced with the error message, and ign.com appears after it, but everything after that fails to appear. And the final array of any 200 messages still doesn't appear. Why does it work like this?
Can anyone share how error handling works in co with generators, etc? Am I seeing expected behaviour with both sets of modifications I've made above? I've read some articles about it but I'm unclear about it.