节点异步-已调用回调-使用2 for循环和if语句 [英] Node Async - Callback was already called - using 2 for loops and an if statement
问题描述
有人可以解释一下为什么我继续看到Error: Callback was already called
的原因.
Could someone please explain why I keep seeing the Error: Callback was already called
.
我觉得我已经涵盖了所有情况-那么为什么会被已经打电话":
I feel I have covered all cases - so why would be 'already called':
function addVertices(outercallback) {
async.forEachLimit(fullData, 25, function (data, innercallback) {
myJson.matches.forEach(function (oMatches) {
if (data.$.id == oMatches.SourceId) {
oMatches.Ids.forEach(function (oId) {
client.execute("g.addV('test').property('id', \"" + oId + "\")", {}, (err, results) => {
if (err) {
return innercallback(console.error(err));
}
innercallback(null)
});
})
}
})
}, outercallback);
}
事实上,我还尝试用async.ForEach
替换第二个forEach,如下所示,但这是正确的方法吗?:
Infact I also tried replacing that second forEach with async.ForEach
as in the following, however is this the correct way to go?:
function addVertices(outercallback) {
async.forEachLimit(fullData, 25, function (data, innercallback) {
async.forEach(myJson, function (oMatches, innercallback2) {
if (data.$.id == oMatches.SourceId) {
oMatches.Ids.forEach(function (oId) {
client.execute("g.addV('test').property('id', \"" + oId + "\")", {}, (err, results) => {
if (err) {
return innercallback2(console.error(err));
}
innercallback2(null)
});
})
}
innercallback(null)
})
}, outercallback);
}
推荐答案
这不是if
的问题.
但是,由于在async.forEachLimit
的每次迭代中,innercallback
在myJson.matches.forEach(...)
中被调用,由于myJson.matches
可能超过一项,因此可能已经多次调用.
But because in each iteration of async.forEachLimit
, the innercallback
is called in the myJson.matches.forEach(...)
which may have been called multiple times since myJson.matches
may be more than 1 item.
第二个代码块中存在相同的问题.
在内部async.forEach
中,innercallback2
在oMatches.Ids.forEach
中被调用,也可以被多次调用.
Same problem in your 2nd code block.
In the inner async.forEach
, the innercallback2
is called in the oMatches.Ids.forEach
which also may be called multiple times.
因此,当您对innercallback
的第二次呼叫(或以后的任何呼叫)发生时,将争辩Error: Callback was already called
.
Therefore, Error: Callback was already called
is argued when your second call (or any later calls) to innercallback
occurs.
我已经用Promise#all
更新了解决方案,以确保在您的原始帖子中调用innercallback
.
请参见 Updated (2018.05.14)
部分和代码块.
I've updated the solution with Promise#all
to ensure the call of innercallback
in your original post.
See the Updated (2018.05.14)
part and the code block.
这篇关于节点异步-已调用回调-使用2 for循环和if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!