Skip to content

Instantly share code, notes, and snippets.

@cicorias
Forked from pasupulaphani/get_resp.js
Last active August 29, 2015 14:25
Show Gist options
  • Save cicorias/de23d8b11f25a38820db to your computer and use it in GitHub Desktop.
Save cicorias/de23d8b11f25a38820db to your computer and use it in GitHub Desktop.
var Fiber = require('fibers')
var getResp = function (url, callback) {
var fn = Fiber(function () {
var resp = handleRequest(url);
if (resp.statusCode != 200) {
//handle success response
} else {
//handle other responses here
}
callback && callback();
});
try {
fn.run();
} catch(e) {
console.log('caught error!', e);
console.log(e.stack);
}
}
var http = require('http');
var Fiber = require('fibers')
module.exports = function handleRequest(url) {
var fiber = Fiber.current;
http.get(url, function(res) {
if (res.statusCode !== 200) {
console.log(url + "returned : ", res.statusCode);
var result = {statusCode: res.statusCode};
fiber.run(result);
} else {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var result = JSON.parse(body);
result.statusCode = res.statusCode
fiber.run(result);
});
}
}).on('error', function(e) {
console.log("error: ", e);
var result = {statusCode: res.statusCode};
fiber.run(result);
});
var resp = Fiber.yield();
return resp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment