避免多層回調,Node.js非同步庫Async使用(series)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.