Skip to content

Instantly share code, notes, and snippets.

@seanhess
Last active December 11, 2015 17:39
Show Gist options
  • Save seanhess/4636018 to your computer and use it in GitHub Desktop.
Save seanhess/4636018 to your computer and use it in GitHub Desktop.
Example of how promises cleaned up my node.js code
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)
})
})
app.post('/books/:bookId/files', function(req, res) {
File.addFileToBook(req.params.bookId, req.files.file)
.then(send(res), err(res))
})
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)
})
})
}
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