Code that was written coffeescript before async was used:
Exports.product_file_add = (req,res)if!req.param (' file_id ') returnRes.json ({' Flag ': ' Error ', ' msg ': ' Please upload the file before saving! ‘}) File_type= Req.param (' File_type ') #判断产品和文件类型, limit the number of uploads params={} Params.product_code= Req.param (' Product_code ') Params.file_type=File_type productfile.count params, (err,count)-ifCount>0returnRes.json ({' Flag ': ' Error ', ' msg ': ' The product's file already exists! ‘}) Product_file=Newproductfile Product_file.add req, (ERR)-iferr Reserr (res,err)ElseRes.json ({' Flag ': ' Success '})
Code written by Coffeescript after using async:
Exports.product_file_add = (req,res)if!req.param (' file_id ') returnRes.json ({' Flag ': ' Error ', ' msg ': ' Please upload the file before saving! ‘}) Async.series ([CB]-#判断产品和文件类型, limit the number of uploads params={} Params.product_code= Req.param (' Product_code ') Params.file_type=File_type productfile.count params, (err,count)-ifCount>0CB (' The file for this product already exists! ‘) ElseCB (NULL) (CB)-Product_file=Newproductfile Product_file.add req, (ERR)-ifErr CB (ERR)ElseCB (NULL)], (err,results)-ifErrreturnRes.json ({' Flag ': ' Error ', ' msg ': Err}) Res.json ({' Flag ': ' Success '}) )
Of course, the code here is not deep enough to see the benefits of using async without going in and out.
Aysnc.series, serial execution of each asynchronous callback function
Execute each function in an array of functions sequentially, before executing the next function after each function is completed.
If any function passes an error to its callback function, the subsequent function is not executed and will immediately pass the error and the result of the executed function to the last callback in the series.
When all the functions have been executed (without error), the result of each function passed to its callback function is combined into an array to pass to the last callback of the series.
You can also provide tasks in the form of JSON. Each property is executed as a function, and the result is passed to the last callback of the series in JSON form. This way is more readable. This passage comes from (http://www.verydemo.com/demo_c441_i206465.html)