我在放一個nodejs應用程序來從我經常使用的網站檢索我的獎項,並且遇到了讓它工作的問題。我試圖找出如何將主題變量作爲參數傳遞給我的profile.get函數。未定義forEach TypeError:undefined不是一個函數
嘗試以下:
users.forEach(profile.get(topic));
結果:
users.forEach(profile.get(topic));
^
TypeError: undefined is not a function
at Array.forEach (native)
app.js
var profile = require("./profile.js");
var topic = process.argv.slice(2,3);
var users = process.argv.slice(3);
users.forEach(profile.get);
個profile.js
function get(username, topic) {
//Connect to API URL (http://url.com/username.json)
var request = https.get("https://url.com/" + username + ".json", function(response) {
var body = "";
//Read the data
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
if (response.statusCode == 200) {
try {
//Parse the data
var profile = JSON.parse(body);
//Print the data
printer.printMessage(username, profile.badges.length, profile.points.topic, topic);
} catch(error) {
//Parse Error
printer.printError(error);
}
} else {
//Status Code Error
printer.printError({message: "There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"});
}
});
});
//Connection Error
request.on('error', printer.printError);
}
更新:
的console.log(用戶);
返回[ 'myuserrname', 'secondusernamehere']
因爲需要將一個函數傳遞給'.forEach()',所以你必須在函數中包裝這個調用。目前還不清楚代碼應該是什麼樣子,因爲它不清楚'users'數組中的內容以及它的內容與調用'profile.get()'函數的方式有什麼關係。 – Pointy