Created
December 9, 2014 19:15
-
-
Save roman01la/31d661c268fff13e145e to your computer and use it in GitHub Desktop.
ES7 async/await
This file contains 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
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); | |
} | |
} |
This file contains 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
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