我正在尝试使用 Koa.js 构建一个简单的 REST API。它使用 ES6 生成器函数,我发现它比回调更令人愉快(它们就像 C# 的 async-await 一样)。yield 关键字需要一个 thenable(promise、thunk、generator)。我正在使用 Bluebird 的 promisifyAll 方法来承诺回调库(在我的情况下是请求),但我仍然不断收到错误消息。这是我的代码和错误:
var koa = require('koa')
, route = require('koa-route')
, app = module.exports = koa()
, Promise = require('bluebird')
, request = Promise.promisifyAll(require('request'));
app.use(route.get('/users', list));
function *list() {
var res = yield request.get('http://backbonejs-beginner.herokuapp.com/users');
this.body = res.body;
}
app.listen(3000);
错误的堆栈跟踪:
Error: yield a function, promise, generator, array, or object
at next (/Users/jashua/Desktop/node_modules/koa/node_modules/co/index.js:109:12)
at Object.<anonymous> (/Users/jashua/Desktop/node_modules/koa/node_modules/co/index.js:50:5)
at next (/Users/jashua/Desktop/node_modules/koa/node_modules/co/index.js:93:21)
at Object.<anonymous> (/Users/jashua/Desktop/node_modules/koa/node_modules/co/index.js:50:5)
at Server.<anonymous> (/Users/jashua/Desktop/node_modules/koa/lib/application.js:121:8)
at Server.EventEmitter.emit (events.js:107:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:504:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_server.js:357:22)
at Socket.EventEmitter.emit (events.js:104:17)
我错过了什么?