2016-02-29 30 views
1

我在放一個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']

+3

因爲需要將一個函數傳遞給'.forEach()',所以你必須在函數中包裝這個調用。目前還不清楚代碼應該是什麼樣子,因爲它不清楚'users'數組中的內容以及它的內容與調用'profile.get()'函數的方式有什麼關係。 – Pointy

回答

6

如果users包含要傳遞給.get()功能的用戶名,然後你的循環應該是這樣的:

users.forEach(function(username) { 
    profile.get(username, topic); 
}); 

.forEach()方法調用你的回調函數,連續傳遞數組中的每個值。如果這些值是用戶名,那麼每個回調的調用都會給你一個用戶名。假設topic值是在你發佈的代碼之外定義的東西,它也會在回調中看到。

在您的嘗試中,您直接呼叫profile.get()並將其返回值轉換爲.forEach()。函數沒有返回值,所以這就是爲什麼.forEach()拋出異常—您通過的回調值是undefined

your previous question about this code中,您正在使用那個只有一個參數的.get()函數的版本。正因爲如此,使用

users.forEach(profile.get); 

工作得很好,因爲你通過了參考.get()功能.forEach(),所以它的工作。然而,在這種代碼:

users.forEach(profile.get(topic)); 

profile.get(topic)呼叫的功能。這是造成問題的原因。在JavaScript中,解決類似問題的方法(至少,最簡單的方法)是在該答案的頂部引入包裝函數。現在,.forEach()很高興,因爲你傳遞了一個函數來調用,而profile.get()很高興,因爲你傳遞了它所期望的兩個參數。

+0

是的,也許一個解釋爲什麼它不爲他工作也會有幫助?例如'profile.get'需要返回一個函數。 –

+0

在我決定添加一個主題之前,它的工作原有方式,所以我不必將用戶名傳遞給forEach,我可以直接調用它,它會知道它。 – user3732216

+1

@ user3732216您不通過用戶名進入'.forEach()'調用; '.forEach()'將用戶名傳遞給* your *函數。 – Pointy

相關問題