我的問題是,我有一個Function A
調用另一個函數,我們稱之爲Function B
(getChildContent)並需要返回值Function B
才能繼續。我知道這是因爲JavaScript異步自然,我試圖用回調來解決它。但我無法正常工作。Javascript回調for循環
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
//var content = getChildContent(caps[y]);
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}}}
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
所以在Function A
我試圖從一個for循環調用getChildContent,並通過從蓋陣列當前字符串。對於caps-array中的每個字符串,getChildContent()通過node.js模塊發出http請求並檢索字符串。有了這個字符串,我正在構建一個需要在Function A
中繼續的對象(內容)。然而,Function A
中的'console.log(content)'只是打印出用caps-array中的最後一個字符串創建的對象,但是多次。例如。如果caps-array有5個條目,我得到5次用caps-array的最後一個條目創建的對象。 我如何管理循環/回調以獲得每次控制檯上正確的對象?
這億韓元當你的回調函數被調用時,你的y變量已經改變了它的值 –
你已經嘗試了'Function.prototype.bind'嗎? – klenium
@ EugenTimm我知道它不工作,你有沒有提示它工作? – dnks23