问题
Im using rethinkdbdash with koa and trying to figure out how to perform a set up of the database when the app first starts. Im trying to accomplish something similar to Segphalt's cats of instagram tutorial but using koa.
var conn;
r.connect(config.database).then(function(c) {
conn = c;
return r.dbCreate(config.database.db).run(conn);
})
.then(function() {
return r.tableCreate("instacat").run(conn);
})
.then(function() {
return q.all([
r.table("instacat").indexCreate("time").run(conn),
r.table("instacat").indexCreate("place", {geo: true}).run(conn)
]);
})
.error(function(err) {
if (err.msg.indexOf("already exists") == -1)
console.log(err);
})
.finally(function() {
r.table("instacat").changes().run(conn)
.then(function(cursor) {
cursor.each(function(err, item) {
if (item && item.new_val)
io.sockets.emit("cat", item.new_val);
});
})
.error(function(err) {
console.log("Error:", err);
});
I've tried to just yield instead of chaining the promises but that throws an error due to invalid syntax.
try {
yield r.dbCreate(config.database.db).run();
yield r.tableCreate('user').run();
}
catch (err) {
if (err.message.indexOf("already exists") == -1)
console.log(err.message);
}
app.listen(port);
What is the best way to perform this type of setup including performing a query that runs the .changes() in koa, so that it only executes once the server starts up and not on every request cycle that comes through. Or is there a better way to accomplish this in koa?
回答1:
You can only use the yield
keyword inside of a generator function (one with an asterisk in the signature). Typically, if you want to use yield
to wait for completion of a promise, you would wrap the entire set of operations with a generator-based coroutine.
There are two libraries that you can use for this:
- Co: https://www.npmjs.com/package/co
- Bluebird: https://www.npmjs.com/package/bluebird
Co is what Koa uses under the hood in all of its middleware handlers, but I personally prefer Bluebird because it seems to have slightly better error handling in my experience.
You can wrap your setup code in a Bluebird coroutine and then call it in place:
bluebird.coroutine(function *() {
try {
yield r.dbCreate(config.database.db).run();
yield r.tableCreate('user').run();
}
catch (err) {
if (err.message.indexOf("already exists") == -1)
console.log(err.message);
}
})();
来源:https://stackoverflow.com/questions/32851452/how-to-perform-initial-setup-in-koa-with-rethinkdb