我有一組遠程文件地址。我只是用於在foreach數組和foreach的主體中,我開始HTTP GET請求數據下載。但是,一切都是異步的,我需要知道文件名以將文件保存在請求回調中。Foreach數組並在回調中使用數組成員
解決此問題的最佳做法是什麼?
演示代碼:
files = ["url.com/file.png", "url.com/file.doc"]
for file in files
req = http.get file, (response) =>
response.setEncoding 'binary'
body = ""
response.on "data", (chunk) =>
body += chunk
response.on "end",() =>
#Here I needs to know the file name to save it
fs.writeFileSync @currentFolder + "/Files/" + file, body, "binary"
謝謝!
什麼問題?你問如何將'url.com/file.png'轉換爲'file.png'? – Eric 2013-04-24 07:52:08
不,根據writeFileSync我需要獲取原始變量「文件」的值。但一切都是異步的,所以變量「文件」將只填寫最後的文件名。 – 2013-04-24 07:55:05
你確定嗎?我認爲coffeescript for loops使用閉包來防止這種問題。 – Eric 2013-04-24 07:57:27