我正在Angular中实现一个Github Commit History Flow Visualizer,它有一个处理webhooks和套接字的Node后端。我正在使用节点包deferred来处理promises,我在函数回调中分配复杂变量时遇到了麻烦。我喜欢承诺,但是这个让我很难过。请参阅下面的代码:
function getGithubRepoData(repoName) {
var d = deferred();
var reponseData = {
branches: { values: [] },
tags: { values: [] },
commits: [{ values: [] }]
}
deferred(getGithubRepoBranches(repoName), getGithubRepoTags(repoName))(function(result) {
console.log("both done");
console.log(result[0]);
console.log("blocking?");
responseData.branches.values = result[0];
console.log("past here?");
responseData.tags.values = result[1];
console.log("now do commits");
getGithubRepoCommits(repoName, result[0]).then(function(result) {
responseData.commits[0].values = result;
d.resolve(responseData);
})
})
return d.promise();
}
此函数显然是为了获取分支,标记和提交(适用于所有分支)。问题在于我尝试分配responseData.branches.values
时。代码在此之前正确执行并挂起,输出以下内容:
both done
4
blocking?
然后什么都没有......
这是一个更简单的概念证明,您可以用它来说明我的问题:
var deferred = require('deferred');
function dtest() {
var d = deferred();
setTimeout(function () {
d.resolve("good");
}, 500);
return d.promise;
}
var reponseData = {
branches: { values: [] },
tags: { values: [] },
commits: [{ values: [] }]
}
var tester = "test";
deferred(dtest())(function(result) {
tester = result;
console.log(result);
console.log("here?");
responseData.branches.values = result;
console.log("here?");
console.log(responseData.branches.values);
})
哪个输出:
good
here?
正如您所看到的,简单的字符串变量没有问题,但更复杂的对象无限期挂起。
此时我怀疑我正在使用的软件包有一些我没有看到的错误,但是我希望有比我更多Node知识的人能够突然进入并指出我陷入困境的地方锁定问题或一些竞争条件。如果这不起作用,我将不得不考虑按顺序运行每个get函数而不是并行。在此先感谢您的帮助!
答案 0 :(得分:1)
在你的第一个代码片段中,你有responseData拼写错误" reponseData"。之后,reponseData未定义。您没有捕获延迟承诺中引发的错误,因此它似乎挂起。