我对Node有点陌生,而对Koa则完全陌生。我正在尝试使用生成器向API发出异步Web请求,但是我不知道如何将所有部分放在一起。
值得注意的是,我使用的是bluebird,因为我看到了一些示例可以做到这一点,这似乎是个好主意。如果没有蓝鸟,有一种更轻松的方式来做我想做的事,那也很好。
在我的模块中:
plugin.searchForItem = function * (name) {
Promise = require('bluebird');
request = Promise.promisifyAll(require('request'));
console.log("making request");
yield request.getAsync('http://apisitegoeshere.com/apicall').then(function * (result) {
var response = result[0];
var body = result[1];
console.log(response.statusCode);
yield response;
});
};
我这样称呼它:
search.searchForShow = function (name) {
data = this.plugins[0].searchForItem(name);
console.log("search returned: " + data);
console.log("search returned2: " + JSON.stringify(data.next()));
console.log("search returned3: " + JSON.stringify(data.next()));
return data;
};
在控制台中查看时,会看到:
search returned: [object Generator]
making request
search returned2: {"value":{"isFulfilled":false,"isRejected":false},"done":false}
search returned3: {"done":true}
我知道我的代码到处都是,但是我已经花了好几个小时来研究它,但我仍然无法解决它。
谢谢!
请不要调用promisifyAll
运行时代码:这是不必要的,应用程序逻辑混乱,不属于其中,并且运行速度非常慢。
您需要将该方法标记为协程,否则它只是一个生成器。
var Promise = require("bluebird");
// Assumes request is promisified else where, like in your init file
var request = require("request");
plugin.searchForItem = Promise.coroutine(function* (name) {
var response = yield request.getAsync("http://www.google.com").get(0);
console.log(response.statusCode);
return response;
});
协程返回一个promise,您可以将其与另一个协程一起使用或仅将其用作promise。由于您已经在使用生成器,因此不妨使用其他协程:
search.searchForShow = Promise.coroutine(function* (name) {
var data = yield this.plugins[0].searchForItem(name);
console.log("search returned: " + data);
return data;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句