Frage

I'm trying to build a simple REST API with Koa.js. It uses ES6 generator functions, which I find much more pleasant than callbacks (they're just like C#'s async-await). The yield keyword expects a thenable (promise, thunk, generator). I'm using Bluebird's promisifyAll method to promisify callback libraries (request in my case), but I still keep getting error. Here are my code and the error:

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);

Stack trace for the error:

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)

What am I missing?

War es hilfreich?

Lösung

Bluebird adds an Async suffix to promisified functions with promisifyAll.

Try:

  var res = yield request.getAsync('http://backbonejs-beginner.herokuapp.com/users');
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top