在重构代码中使用fetch

时间:2018-05-16 20:17:35

标签: javascript promise fetch

当我在一个文件中写字时,我已经能够绕着WebRequest的{​​{1}}包围,但是一旦我开始将代码拆分成多个文件,我就会卡住。这已经发生了几次,我必须要丢失或转置一些概念。

这是在node.js。

的上下文中

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

Promise

然后在我使用此功能的文件中:

fetch

而且,它只是吐出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]

1 个答案:

答案 0 :(得分:0)

您正在返回功能res.json而不是res.json()承诺

替换

.then( res => res.json)

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

另外

Repalce

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