无法弄清楚如何在异步请求中使用yield

傻瓜

我对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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法弄清楚如何使用lighttpd接收HTTP请求

无法弄清楚如何在Jssor Slider中使用导航器

无法弄清楚如何在WebService中使用参数MaxReceivedMessageSize

无法弄清楚如何在CachéSQL中使用MODULO / MODULUS函数

无法弄清楚如何在C ++中使用winapi设置EM_SETLIMITTEXT的值

无法弄清楚如何使用 IF 语句

无法弄清楚如何在二进制Web套接字中使用缓冲区

无法弄清楚如何在样式化组件和useState挂钩中使用props更改css

我无法弄清楚如何在瓶子请求中共享会话

Discord.py:无法弄清楚如何使用aiohttp代替此用例的请求

无法弄清楚如何使用 ffi 在 Dart 中使用 SetWindowsHookEx

无法弄清楚如何在Java中重叠图像

无法弄清楚如何在地图中检索对象

如何弄清楚布局在项目中使用的位置?

很难弄清楚如何在 Java 的 for 循环中使用用户输入

无法弄清楚如何使用Spring Data REST端点

JAXB-无法弄清楚如何正确使用refID

无法弄清楚如何使用$ scope。$ watch

无法弄清楚如何正确使用KeyboardAvoidingView

无法弄清楚如何使用ImageViewTouch挂钩

无法弄清楚如何使用 OfficeExtension.Promise

无法弄清楚如何正确使用reduce

无法弄清楚如何使用AppleScript实现REGEX

无法弄清楚如何使用通用UpdateView呈现ModelForm

无法弄清楚如何使用getchar(); 在C中

无法弄清楚如何为我的函数使用参数

无法弄清楚如何使用西班牙口音

我无法弄清楚如何在JAVA中正确使用“尝试”

无法弄清楚如何在ORDER BY子句中正确使用CASE WHEN语句