【问题标题】:request-promise implementation returning `null`请求承诺实现返回“空”
【发布时间】:2015-12-23 21:22:17
【问题描述】:

鉴于下面的代码示例,任何想法为什么从getBatchedContent 返回的值是null

import rp from 'request-promise';
import _ from 'lodash';

function getBatchedContent(size, page) {
  return Promise.resolve(fetchBatchedContent(size, page)); // Getting `null` here.
}

function fetchBatchedContent(size, page) {
  var options = {
    uri: `http://www.example.com/posts?type=vogue-fashion-shows&filter[posts_per_page]=${size}&page=${page}`
  };

  return rp(options)
    .then(function (res) {
      res = JSON.parse(res);
      // res is an array of content objects.
      return _.map(res, function (obj) { // logged value of `_.map()` is correct.
        return transformContent(obj);
      });
    });
}

function transformContent(obj) {
  return {
    id: obj.ID,
    title: obj.title,
    // etc.
  };
}

【问题讨论】:

  • 仅供参考,getBatchedContent() 不会为您提供任何其他功能。您可以直接调用fetchBatchedContent() 并获得相同的结果。
  • 如果您正在谈论已解决的承诺值是 null,那么我会查看您的 rp(...).then() 处理,看看它是否真的在做您期望的事情并实际返回所需的值.

标签: javascript request return promise lodash


【解决方案1】:

也许将.catch(function (error) {debugger;}) 添加到fetchBatchedContent。它会返回您期望的结果吗?

我不确定您在Promise.resolve 中输入的内容是否会直接导致null?这对我来说似乎很奇怪,即使Promise.resolve(Promise.reject('foo')) 也会返回一个 Promise。 (被拒绝的)。

【讨论】:

  • 嗯...我应该澄清 null 值是由 hapi 返回的 json 响应冒泡的。我试图让实施的那一部分排除在外,以隔离问题的原因。但是...在fetchBatchedContent 正文中的return 语句中的then 之后添加catch 不会导致任何捕获的错误。
  • 所以getBatchedContent返回的Promise,解析为null?
猜你喜欢
  • 2017-05-15
  • 2017-02-22
  • 2018-04-10
  • 1970-01-01
  • 2017-07-10
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
相关资源
最近更新 更多