Skip to content

Instantly share code, notes, and snippets.

@Kequc
Last active June 2, 2016 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kequc/bcd80980184ed480b864581bcdb351f4 to your computer and use it in GitHub Desktop.
Save Kequc/bcd80980184ed480b864581bcdb351f4 to your computer and use it in GitHub Desktop.
Callback hell example
router.post('/:id/title-image', (req, res, next) => {
lwip.open(req.file.buffer, 'jpg', (err, image) => {
if (err) { next(err); return; }
let ratio = (image.width() > 960 ? (960 / image.width()) : 1);
image.scale(ratio, (err, image) => {
if (err) { next(err); return; }
image.crop(image.width(), Math.min((image.width() / 2), image.height()), (err, image) => {
if (err) { next(err); return; }
image.toBuffer('jpg', { quality: 80 }, (err, buffer) => {
if (err) { next(err); return; }
db.doc.attachment.write(req.params['id'], "TITLE_IMAGE", buffer, "image/jpeg", (err) => {
if (err) { next(err); return; }
res.sendStatus(200);
});
});
});
});
});
});
function processTitleImage (file, callback) {
if (!file) {
callback(new Error("No file"));
return;
}
let type = file.originalname.split('.').pop();
lwip.open(file.buffer, type, (err, image) => {
if (err) { callback(err); return; }
let ratio = (image.width() > 960 ? (960 / image.width()) : 1);
let width = image.width() * ratio;
let height = image.height() * ratio;
async.series({
scale: image.scale.bind(image, ratio),
crop: image.crop.bind(image, width, Math.min((width / 2), height)),
buffer: image.toBuffer.bind(image, 'jpg', { quality: 80 })
}, callback);
});
}
router.post('/:id/title-image', (req, res, next) => {
processTitleImage(req.file, (err, result) => {
if (err) { next(err); return; }
db.doc.attachment.write(req.params['id'], "TITLE_IMAGE", result.buffer, "image/jpeg", (err) => {
if (err) { next(err); return; }
res.sendStatus(200);
});
});
});
function processTitleImage (file, callback) {
if (!file) {
callback(new Error("No file"));
return;
}
let type = file.originalname.split('.').pop();
lwip.open(file.buffer, type, (err, image) => {
if (err) { callback(err); return; }
let ratio = (image.width() > 960 ? (960 / image.width()) : 1);
let width = image.width() * ratio;
let height = image.height() * ratio;
image.batch()
.scale(ratio)
.crop(width, Math.min((width / 2), height))
.toBuffer('jpg', { quality: 80 }, callback);
});
}
router.post('/:id/title-image', (req, res, next) => {
processTitleImage(req.file, (err, buffer) => {
if (err) { next(err); return; }
db.doc.attachment.write(req.params['id'], "TITLE_IMAGE", buffer, "image/jpeg", (err) => {
if (err) { next(err); return; }
res.sendStatus(200);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment