1
變量的作用域,我有以下代碼:的CoffeeScript上node_redis hgetall回調函數
genUserLeagueDiscussionTable = (userLeagueId, firstEntry, displayEntries) ->
# Generate League Discussion
leagueDiscussionTable =
striped: yes
bordered: yes
hover: no
condensed: yes
columns: [{head:"Name"}, {head:"Comments"}]
console.log "get userLeague #{userLeagueId}"
LeagueId = userLeagueId
getLeagueDiscussionEntries = (entry, callback) =>
getDiscussionEntry = (err,cnreply) ->
setDiscussionTableRows = (err,replyObj,request) ->
leagueDiscussionTable.rows[entry.dataentrynum].data = [replyObj.nickname,cnReply.entryText]
console.log "Reply received for entry ",entry.entrynum
console.log cnreply.entryText
loginclient.hgetall 'uid:'+cnReply.postingUid, setDiscussionTableRows
callback()
lookupentry = entry.lookupentry
console.log "getting entry for ", entry, " database key ", lookupentry
leagueclient.hgetall lookupentry, getDiscussionEntry
getLeagueInfo = (err,lreplyObj) =>
console.log "got league info", lreplyObj
leagueDiscussionTable.caption = lreplyObj.leagueName+" League Info"
console.log "caption", leagueDiscussionTable.caption
leagueDiscussionEntries = lreplyObj.currentDiscussionEntry
console.log "Caption ",leagueDiscussionTable.caption," entries ", leagueDiscussionEntries, " Display Entries ",displayEntries
lastEntry = Math.min(leagueDiscussionEntries,firstEntry+displayEntries)
console.log "start entry ", firstEntry, " last entry ", lastEntry
entries=[]
for num in [firstEntry..lastEntry]
console.log num,".a"
entries[num]={}
entries[num].entrynum=num
console.log num,".b"
entries[num].lookupentry="userLeagueId:#{LeagueID}:discussionEntryId:#{entry}"
console.log num,".c"
entries[num].dataentrynum = num-firstEntry
console.log num," ", entries[num]
console.log "Lookup the entries ", entries
async.forEach entries, getLeagueDiscussionEntries
, (err,reply) ->
console.log "callback 1"
leagueclient.hgetall "userLeagueId:#{LeagueId}", getLeagueInfo
return leagueDiscussionTable
不管我做什麼,我無法訪問LeagueId或userLeagueId在getLeagueInfo。它可以在外部包裝器中正常工作,但我無法在回調函數中訪問它。
我在做什麼錯?
感謝您的幫助。
[編輯]有沒有辦法讓我通過hgetall調用回調函數作爲參數傳遞給函數?
弗雷德
因此,工作,但我不知道爲什麼。任何人都有一個好的指針,可以幫助我在哪裏使用@(this)引用這種類型的東西的在線課程? –
在您的示例中,您將'genUserLeagueDiscussionTable'定義爲一個具有'getLeagueInfo'作爲其方法的對象。您將'getLeagueInfo'作爲'hgetall'的回調函數傳遞,但是當它被回調時,'LeagueId'創建的範圍不再可用。更改爲'@ leagueId'使其成爲'genUserLeagueDiscussionTable'的一個屬性,當您位於'getLeagueInfo'內時可以通過'this'訪問,它指向正確的'this',因爲在定義它時使用了'=>'符號。當您使用回調來存儲實例變量以便在回調中訪問時使用'@'。 –