標籤:style blog http color 使用 strong
未使用Async之前coffeescript寫的代碼:
exports.product_file_add = (req,res) -> if !req.param(‘file_id‘) return res.json({‘flag‘:‘error‘,‘msg‘:‘請先上傳檔案再儲存!‘}) file_type = req.param(‘file_type‘) #判斷產品和檔案類型,限制上傳的數量 params = {} params.product_code = req.param(‘product_code‘) params.file_type = file_type ProductFile.count params,(err,count) -> if count>0 return res.json({‘flag‘:‘error‘,‘msg‘:‘該產品的檔案已存在!‘}) product_file = new ProductFile product_file.add req,(err)-> if err resErr(res,err) else res.json({‘flag‘:‘success‘})
使用Async之後coffeescript寫的代碼:
exports.product_file_add = (req,res) -> if !req.param(‘file_id‘) return res.json({‘flag‘:‘error‘,‘msg‘:‘請先上傳檔案再儲存!‘}) async.series([ (cb)-> #判斷產品和檔案類型,限制上傳的數量 params = {} params.product_code = req.param(‘product_code‘) params.file_type = file_type ProductFile.count params,(err,count) -> if count>0 cb(‘該產品的檔案已存在!‘) else cb(null) (cb)-> product_file = new ProductFile product_file.add req,(err)-> if err cb(err) else cb(null) ], (err,results)-> if err return res.json({‘flag‘:‘error‘,‘msg‘:err}) res.json({‘flag‘:‘success‘}) )
當然這裡的代碼嵌套不深,不太能看不進出使用Async的好處。
Aysnc.series,串列執行每一個非同步回調的函數
依次執行一個函數數組中的每個函數,每一個函數執行完成之後才能執行下一個函數。
如果任何一個函數向它的回呼函數中傳了一個error,則後面的函數都不會被執行,並且將會立刻會將該error以及已經執行了的函數的結果,傳給series中最後那個callback。
當所有的函數執行完後(沒有出錯),則會把每個函數傳給其回呼函數的結果合并為一個數組,傳給series最後的那個callback。
還可以json的形式來提供tasks。每一個屬性都會被當作函數來執行,並且結果也會以json形式傳給series最後的那個callback。這種方式可讀性更高一些。這段話來源於(http://www.verydemo.com/demo_c441_i206465.html)