Last active
December 11, 2015 17:39
-
-
Save seanhess/4636018 to your computer and use it in GitHub Desktop.
Example of how promises cleaned up my node.js code
This file contains hidden or 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
app.post('/books/:bookId/files', function(req, res) { | |
File.addFilesToBook(req.params.bookId, req.files.file, function(err, files) { | |
if (err instanceof Error) return res.send(500, err.message) | |
res.json(files) | |
}) | |
}) |
This file contains hidden or 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
app.post('/books/:bookId/files', function(req, res) { | |
File.addFileToBook(req.params.bookId, req.files.file) | |
.then(send(res), err(res)) | |
}) |
This file contains hidden or 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
export function addFileToBook(bookId:string, uploadedFile:IUploadFile, cb:(err:Error, file:IFile) => void) { | |
var file = toFile(bookId, uploadedFile) | |
uploadToUrl(file, uploadedFile, function(err) { | |
if (err) return cb(err, null) | |
insert(file).run(function(err) { | |
if (err instanceof Error) return cb(err, null) | |
cb(null, file) | |
}) | |
}) | |
} |
This file contains hidden or 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
export function addFileToBook(bookId:string, uploadedFile:IUploadFile):q.IPromise { | |
var file = toFile(bookId, uploadedFile) | |
return uploadToUrl(file, uploadedFile) | |
.then(() => db.run(insert(file))) // return a promise here, will happen async | |
.then(() => file) // makes it finally "return" the file | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment