Skip to content

Instantly share code, notes, and snippets.

@justsml
Forked from Tinusw/myController.js
Last active August 29, 2018 02:43
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 justsml/a18928a9f1305d8b09570a8906a868eb to your computer and use it in GitHub Desktop.
Save justsml/a18928a9f1305d8b09570a8906a868eb to your computer and use it in GitHub Desktop.
a promise example
const mongoose = require('mongoose');
const Store = mongoose.model('Store');
const StoreB = mongoose.model('StoreB');
// Tells package to use es6 promises
mongoose.Promise = global.Promise;
exports.createStore = (req, res, next) => {
const store = new Store(req.body);
const itemB = StoreB
.findOne({ id: req.params._id})
// Tighter Express Pattern:
.catch(next);
// Standard re-throw, technically not needed here*
// .catch(err => {
// throw Error(err); // Needs `new`, or no stack trace is created,
// });
// This line wont work, record_we_want_to_associate is a promise, not a StoreB
// store.storeb_id = record_we_want_to_associate._id
// For a dependent task, we access `record_we_want_to_associate`/itemB with `.then()`:
itemB
.then(record => {
store.storeb_id = record._id;
return store.save()
// after save return all records
.then(stores => Store.find())
// then display them on index page
.then(stores => res.render('index', {stores: stores}))
})
// deal with errors
.catch(next);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment