【问题标题】:using fetch in refactored code在重构代码中使用 fetch
【发布时间】:2018-05-17 04:43:18
【问题描述】:

当我在一个文件中写入时,我已经能够绕过Promisefetch,但是一旦我开始将代码拆分为多个文件,我就会卡住。这种情况已经发生了几次,我一定是遗漏了或转换了一些概念。

这是在 node.js 的上下文中。

我已将我的 Promise 代码放在一个单独的文件中:

module.exports = function(url, branch) {
  return fetch(url)
  .then( res => res.json())
  // here's the meat and potatoes.
  .then( data => data => Object.keys(data.values).filter( value => value.source.branch === branch))
  .catch( err => console.log(err))
};

然后在我使用这个函数的文件中:

const getDescription = require('./get_description');
getDescription(url, branch )
// This is where I want to use this value.
  .then( desc => console.log(desc) )
  .catch( err => console.log(err) );

而且,它只是吐出[Function]

当我把所有东西放在一起时,我似乎能够得到我需要的东西,但我也在做一些奇怪的事情,我将res.json().then 嵌套在另一个里面。

fetch(`https://api.bitbucket.org/2.0/repositories/${circle_project_username}/${circle_project_reponame}/pullrequests`, {headers: {Authorization: auth}})
  .then((res) => {
    res.json().then((data) => {
      Object.keys(data.values).forEach(key => {
        if (data.values[key].source.branch.name === branch) {
          console.log(data.values[key].description);
        }
      })
    })
  })
 .catch(res => console.log(res));

【问题讨论】:

  • 从任何地方删除这些.catch(err => console.log(err) );s - 你只是通过处理这些错误而不实际处理它们来制造混乱的流程!
  • 你有一个错字.then( res => res.json)

标签: javascript promise fetch


【解决方案1】:

您正在返回函数 res.json 而不是 res.json() 承诺

替换

.then( res => res.json)

.then( res => res.json())

还有

替换

.then( data => data => Object.keys(data.values).filter( value => value.source.branch === branch))

 .then( data => Object.keys(data.values).filter( value => value.source.branch === branch))

【讨论】:

  • 不错的收获,但这不会改变结果
  • @icicleking 更新我的答案。我认为您的代码中还有另一个错误,您返回的是函数而不是过滤后的数组/数据
猜你喜欢
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2016-02-09
  • 2013-02-21
相关资源
最近更新 更多