Essentially I'm trying to make an http request with my koa application and was wondering what exactly I would doing wrong
var request = require('koa-request');
var beatsGen = beats();
var response1 = beatsGen.next().value;
function *beats (){
var options = {
url: 'https://api.github.com/repos/dionoid/koa-request',
headers: { 'User-Agent': 'request' }
};
var response = yield request(options);
}
When I console log response1 this is what I get
respone from beats is function (callback) {
_request(uri, options, function (error, response, body) {
callback(error, response);
})
}
I figured response1 would be someType of object containing the body parameter of the callback not the function itself. So why am I getting the function as the generators .next().value?
I'm new to generators and koa so I'm assume I'm making a stupid mistake here.
1 Answer 1
koa-request or any other library that returns thunks or promises/thenables for asynchronous calls is meant to be used with a co-routine library like co or the koa web application framework, which uses co to handle generator-based control flow.
ECMAScript 6 generators are not async-aware but ECMAScript 7 will have async and await to handle this natively.
The statement
var response1 = beatsGen.next().value;
returns the value returned by the first yield statement in beats, which is the thunk returned by request(options). A co-routine-aware library will inspect the return value from generator.next().value and wait for the callbacks to execute or thenables to resolve before resuming the generator body by calling generator.next() again.
Such a library is co:
var request = require('koa-request'),
co = require('co');
function beats (){ //doesn't have to be a generator function
var options = {
url: 'https://api.github.com/repos/dionoid/koa-request',
headers: { 'User-Agent': 'request' }
};
return request(options); //return the thunk
}
co(function *() {
var response1 = yield beats;
//use response
})
If this is meant to be used with koa:
app.use(function *() {
this.body = yield beats();
});
BTW, koa-request would be better named co-request since all co-routine wrappers are prefixed with co-.