Although tricks were a good idea, in my opinion, Promise is the best long-term approach. Many libraries are already moving on to promises for async instead of the old callback(err, data) standard node, and they are dead - just wrap around any asynchronous code to make a promise. Other developers will have experience with promises and, of course, will understand your code, while most will have to look for what is "thunk".
eg. here I wrap jsdom in no promise, I promise, so I can concede it in the koa generator.
const jsdom = require('node-jsdom'); const koa = require('koa'); const app = koa();β app.use(function *() { this.body = yield new Promise((resolve, reject) => jsdom.env({ url: `http://example.org${this.url}`, done(errors, { document }) { if (errors) reject(errors.message); resolve(`<html>${document.body.outerHTML}</html>`); }, })); });β app.listen(2112);
Semantically, promises and generators go hand in hand to really clarify asynchronous code. The generator can be re-entered many times and given several values, while the promise means "I promise that I will have some data for you later." Combined, you get one of the most useful things about Koa: the ability to give both promises and synchronous values.
edit: here is your original example wrapped in Promise to return:
const router = require('koa-router'); const { load } = require('some-other-lib'); const app = koa(); app.use(router(app)); app.get('load', loadjson); function* loadJson() { this.body = yield new Promise(resolve => { load(result => resolve(result)); }); }
Josh from qaribou
source share