Skip to content

Instantly share code, notes, and snippets.

@mattisa
Last active February 6, 2017 10:28
Show Gist options
  • Save mattisa/8fbaf261b18408d22cb423d95adfe763 to your computer and use it in GitHub Desktop.
Save mattisa/8fbaf261b18408d22cb423d95adfe763 to your computer and use it in GitHub Desktop.
Sample to chain async calls
import seeder from './seeder';
seeder({ model: 'User' })
.clear()
.seed()
.fail()
.clear()
.catch((err:Error) => {
console.log( err.stack )
console.error('chain catch');
});
import * as mongoose from 'mongoose';
const seeder = (config: any, promise: Promise<any> = Promise.resolve()) => {
const _exec = (f: () => any) => {
return seeder(config, promise.then(f).catch((err) => {
return Promise.reject(err);
}));
}
return {
clear: () => {
return _exec(() => {
const model = require(`../models/${config.model.toLowerCase()}.model`)[config.model];
return model.remove().exec();
});
},
seed: () => {
return _exec(() => {
const model = require(`../models/${config.model.toLowerCase()}.model`)[config.model];
const entities = require(`./${config.model.toLowerCase()}s`).default;
return model.create(entities);
});
},
fail: () => {
return _exec(() => {
return Promise.reject(new Error('reason!!!'))
})
},
catch: (f: any) => {
promise.catch(f);
}
};
}
export default seeder;
export default [{
firstName: 'Some',
lastName: 'Person',
cv: {
description: 'nested model'
}
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment