【发布时间】:2018-05-17 04:43:18
【问题描述】:
当我在一个文件中写入时,我已经能够绕过Promise 和fetch,但是一旦我开始将代码拆分为多个文件,我就会卡住。这种情况已经发生了几次,我一定是遗漏了或转换了一些概念。
这是在 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