我正在尝试使用Koa.js构建一个简单的REST API。它使用ES6生成器函数,我觉得它比回调更令人愉快(它们就像C#的async-await一样)。 yield关键字需要一个soable(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)
我错过了什么?
答案 0 :(得分:3)
Bluebird使用promisifyAll为promisified函数添加Async
后缀。
尝试:
var res = yield request.getAsync('http://backbonejs-beginner.herokuapp.com/users');