Koa - 提供静态文件的更清洁的异步方式?

Koa - Cleaner Async way to serve static files?

var app = require('koa')();
var router = require('koa-router')();    
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));

router
  .get('*', function *(next) {
    fs.readFileAsync('static/home.html','utf8')
      .then(function(data){ 
          console.log(data)
      });
  });

koa.use(router.routes());

koa.listen(8888);

我有上面的工作,因为我想使用 bluebird promises,但是,有没有更像同步的方式(同时仍然是异步的)来做到这一点?

A-la:

router
  .get('*', function *(next) {
    var data = fs.readFile('static/home.html','utf8');
    console.log(data);
  });

一开始我打算使用 thunk,但听说 co 不会继续支持它。那么还有另一种方法可以做到这一点吗?比如使用发电机之类的? 我知道我可以 yield 上面的函数暂停,但这并不能保证操作在它返回时已经完成,对吗?

co 会屈服于承诺,所以你的第二个例子几乎是完美的。您可能只需要在 fs.readFileAsync 调用中添加一个 yield 语句。像这样:

router
  .get('*', function *(next) {
    var data = yield fs.readFileAsync('static/home.html','utf8');
    console.log(data);
  });