2013-10-31 23 views
1

當我試圖讓使用async.js

testFunction:() -> 
    console.log "testFunction" 
    async.series(
    (-> 
     console.log "first" 
    ), 
    (-> 
     console.log "second" 
    ) 
) 

我也一直在努力,沒有成功

testFunction:() -> 
    console.log "testFunction" 
    async.series(
    (-> 
     console.log "first" 
     return undefined 
    ), 
    (-> 
     console.log "second" 
     return undefined 
    ) 
) 

運行如何處理的CoffeeScript隱含回報,我希望控制檯「testFunction」,「first」,「second」的輸出,但我得到了「testFunction」,「second」,它似乎有一個與coffeescript使用隱式返回問題(我猜)。

附加是從上面的coffeescript編譯的JavaScript輸出的屏幕截圖。

enter image description here

回答

5

每一個函數,它的異步工作需要採取一個回調作爲其唯一參數。

one = (callback) -> 
    console.log "one" 
    callback() 

two = (callback) -> 
    console.log "two" 
    callback() 

testFunction:() -> 
    console.log "testFunction" 
    async.series [one, two], (error) -> 
    console.log "all done", error 
+0

這是一個非常有用的答案謝謝。這是我感到沮喪的一點,現在一直在看文檔,而且我不清楚是否需要這樣做。如果你不能傳入參數,如何給閉包參數中的函數? – John

+0

所以這個故事有點複雜,但我想保持簡單。從技術上講,你可以使用async.apply並接受幾個參數,但最後一個總是回調,它告訴異步「我完成了」。 –

3

你有很多問題。首先是你沒有把正確的論點傳遞給async.series。該公司預計:

async.series([functions...], callback) 

,當你調用

async.series(function, function) 

因爲第一功能的length屬性是不確定的,它假定它的空數組和直接跳到「回調」(第二功能)。這聽起來像你可能想要傳遞兩個函數的數組,並省略回調。

第二個問題是傳遞給async.series的函數必須調用回調才能繼續進行。回調的第一個參數每一個功能:

testFunction:() -> 
    console.log "testFunction" 
    async.series([ 
    ((next) -> 
     console.log "first" 
     next() 
    ), 
    ((next) -> 
     console.log "second" 
     next() 
    ) 
    ]) 

async忽略的,你傳遞給它的大多數(全部?)函數的返回值。

+0

這也是一個很好的答案,謝謝。 – John