Skip to content

Instantly share code, notes, and snippets.

@roman01la
Created December 9, 2014 19:15
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 roman01la/31d661c268fff13e145e to your computer and use it in GitHub Desktop.
Save roman01la/31d661c268fff13e145e to your computer and use it in GitHub Desktop.
ES7 async/await
class DB {
constructor (name) {
this.name = name;
this.collections = {};
this.async = function (callback, timeout) {
return new Promise((resolve, reject) => {
if (!callback) { return reject('Error!'); }
setTimeout(() => {
resolve(callback());
}, timeout);
});
};
}
createCollection (name) {
return this.async(() => {
return this.collections[name] = [];
}, 2000);
}
putDoc (coll, doc) {
return this.async(() => {
return this.collections[coll].push(doc);
}, 300);
}
getAllDocs (coll) {
return this.async(() => {
return this.collections[coll];
}, 1000);
}
}
var db = new DB('test');
async function processThings (num) {
try {
await db.createCollection('things');
for (let i = 0; i < num; i++) {
await db.putDoc('things', { _id: i, title: 'Document_' + i });
}
var things = await db.getAllDocs('things');
return things;
} catch (error) {
return new Error(error);
}
}
processThings(5).then(function (things) {
console.log(things);
}).catch(function (err) {
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment