Node.js:针对"yield"关键字的回调函数库 [英] Node.js: promisifying callback library for 'yield' keyword

查看:106
本文介绍了Node.js:针对"yield"关键字的回调函数库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Koa.js构建一个简单的REST API.它使用ES6生成器函数,我发现它比回调要好得多(它们就像C#的async-await一样). yield关键字期望一个可调整的(promise,thunk,generator).我正在使用Bluebird的promisifyAll方法来实现回调库(在我的情况下是请求),但是我仍然不断出错.这是我的代码和错误:

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

错误的堆栈跟踪:

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)

我想念什么?

推荐答案

Bluebird向带有promisifyAll的函数中添加了Async后缀.

Bluebird adds an Async suffix to promisified functions with promisifyAll.

尝试:

  var res = yield request.getAsync('http://backbonejs-beginner.herokuapp.com/users');

这篇关于Node.js:针对"yield"关键字的回调函数库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆