Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在重构代码中使用fetch_Javascript_Promise_Fetch - Fatal编程技术网

Javascript 在重构代码中使用fetch

Javascript 在重构代码中使用fetch,javascript,promise,fetch,Javascript,Promise,Fetch,当我在一个文件中编写代码时,我已经能够对fetch的承诺了如指掌,但一旦我开始将代码拆分成多个文件,我就会陷入困境。这种情况已经发生过好几次了,我肯定是遗漏了或是转换了一些概念 这是在node.js的上下文中 我已将我的承诺代码放在一个单独的文件中: module.exports = function(url, branch) { return fetch(url) .then( res => res.json()) // here's the meat and potatoe

当我在一个文件中编写代码时,我已经能够对
fetch
承诺了如指掌,但一旦我开始将代码拆分成多个文件,我就会陷入困境。这种情况已经发生过好几次了,我肯定是遗漏了或是转换了一些概念

这是在node.js的上下文中

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

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) );
而且,它只是吐出
[函数]

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

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));

您返回的是函数
res.json
,而不是
res.json()

替换

.then( res => res.json)

修理

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


删除这些
.catch(err=>console.log(err))来自任何地方-通过处理这些错误而不实际处理它们,您只是在制造混乱的流!您有一个输入错误
。然后(res=>res.json)
很好的捕获,但这不会改变outcome@icicleking更新我的答案。我认为您的代码中还有另一个错误,您返回的是函数,而不是经过过滤的数组/数据
.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))