网络科技

    今日:400| 主题:244809
收藏本版
互联网、科技极客的综合动态。

[其他] Avoid callbacks in Node.js with Bluebird promises

[复制链接]
凡尔赛的Rose 发表于 2016-10-11 20:22:29
103 4

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
In this article:Common callback usage patterns would be replaced with idiomatic Bluebird   
          Required knowledge:Basic Node.js experience, basic experience with Promises   
    Basic usage – sequence of tasks:

  1. ⟨ ⟩ CallbackSequence.js
复制代码
const  fs  =  require(  'fs'); fs.  readFile(  'someFile.txt',  'utf8',  function(err, fileContent) {  if(err) {  throwerr;  // Actually ends process} fs.  readFile(fileContent,  function(err, image) {  if  (err) { throw err; }
  doStuff
  (image); }); });
  VS.
  1. ⟨ ⟩ PromiseSequence.js
复制代码
const  Promise  =  require(  'bluebird');  const  fs  =  Promise.  promisifyAll(  require(  'fs')); fs.  readFileAsync(  'someFile.txt',  'utf8') .  then(fileContent  =>fs.  readFileAsync(fileContent)) .  then(doStuff); .  catch(err  =>  {
  // Handle all errors in one place
  });
  As we can see, maximal nesting level is reduced. Error handling point is well-defined, so we can’t make a mistake while handling errors – like passing error to bad higher-level callback.
  Branching

  Promise based solution isn’t silver-bullet. To be honest I had to include common use case of branching when Promise based solution is only barely better than callback based flow.
  1. ⟨ ⟩ BranchingCallback.js
复制代码
const  basicArithmeticsAsService  =  require(  'fictional-service'); basicArithmeticsAsService.  add(  2,  2, (err, response)  =>{  if(err) {  return  someCallback(  new  TypeError(  'Network issues'  : +err.message)); }  if(response.  status  ===  200) {  returnbasicArithmeticsAsService.  multiply(response.  body,  4, (err, response)  =>{  if(err) {  return  someCallback(  new  TypeError(  'Network issues'  : +err.message)); }  else if(response.  status  ===  200) {  return  someCallback(  null, response.  body) }  else{  someCallback(  null,  NaN); } }) }  else{  someCallback(  null  ,
  NaN
  ); } });
  VS.
  1. ⟨ ⟩ BranchingPromise.js
复制代码
const  basicArithmeticsAsService  =  require(  'fictional-service'); basicArithmeticsAsService.  addAsync(  2,  2) .  then((response)  =>{  if(response.  status  ===  200) {  returnbasicArithmeticsAsService.  multiplyAsync(response.  body,  4) .  then(response  =>{  if(response.  status  ===  200) {  returnresponse.  body; }  else{  return  NaN; } }) }  else{  return  NaN; } }) .  catch(err  =>{  throw new  TypeError(  'Network issues'  : +
  err.message); });
  Async.js

  Async.js became the industry standard for handling callbacks before Promises went viral. Today, most of async.js utilities can be replaced with idiomatic usage of advanced Promise implementations, with all of it richness – promisification, convenient adapters for callbacks, long stack traces.
  Let’s analyze basic asynchronous flows:
  1. ⟨ ⟩ AsyncFilter.js
复制代码
const  fs  =  require(  'fs');  const  async  =  require(  'async');  async.  filter([  'file1',  'file2',  'file3'],  function(filePath, callback) { fs.  access(filePath,  function(err) {  callback(  null,  !err) }); },  function  (err, results){
  // results now equals an array of the existing files
  });
  VS.
  1. ⟨ ⟩ BluebirdFilter.js
复制代码
const  Promise  =  require(  'bluebird');  const  fs  =  Promise.  promisifyAll(  require(  'fs'));  Promise.  filter([  'file1',  'file2',  'file3'] , path=>fs.  accessAsync(path)) .  then  (results
  =>
  { });
  Bluebird exposes common array operations like    map,    filter,    each. These methods take 3 arguments – array (or Promise resolving to array), function applied to each element and concurrency – maximal number of functions running at once, in manner similar to async.fnLimit family.  
  Some async.js methods for collections can’t be emulated using basic Promise-based code – methods like ‘sortBy’, ‘transform’ tend to be pain in ass. We’ll discuss how to marry async.js and Bluebird later.
  Retry

  It’s often convenient to retry failed task. It’s quite easy to write in synchronous manner, but writing it in asynchronous way can be mind-boggling, especially when concurrency or parallelism comes in the hand.
  1. ⟨ ⟩ RetryCallback.js
复制代码
const  async  =  require(  'async');  retry(  5, done  =>  getResource(url, done), (err, result)  =>{  if  (err)
  throw
  err; })
  VS.
  1. ⟨ ⟩ RetryPromise.js
复制代码
const  async  =  require(  'async');  function  retry(n  =  5, task) {  return  Promise.  resolve().  then(task).  catch(err  =>{  if(n  >  1)  return  retry(n  -  1, task);  throwerr; }); }  retry(()  =>  getResourceAsync
  (url));
  Bluebird offers better solution than callback based approach, because of it’s superior resource management. Consider this code:
  1. ⟨ ⟩ RetryResourceCallback.js
复制代码
function  retry(fn, maxRetries, complete) {  fn((err, res)  =>{  if(err) {  if(  !maxRetries) {  complete(err); }  else{  retry(fn, maxRetries  -  1, complete); } }  else{  complete(err, res); } }) }  retry(complete  =>{  return async.  parallel([ aquireResource, aquireOtherResource ], complete); },  5  ,
  console
  .log)
  Can you see what is wrong with this code? It runs to successful completion of all tasks, or first rejection. If acquiring resource is time-consuming, we’ll introduce to our code race conditions – code execution (in our case – retry) will continue regardless if non-faulty task released it’s resources.
  Bluebird offers powerful mechanisms to prevent this issue. Disposers allow us to automatically clean resources, similar to RAII pattern, but for better comparision with async we will assume that our functions task1 and task2 clean their resources on completed execution.
  1. ⟨ ⟩ RetryResourcePromise.js
复制代码
function  settleAll(promises) {  return  Promise.  all(promises.  map(promise  =>  Promise.  resolve(promise).  reflect())) .  then(  function(results) {  const  err  =results.  find(e  =>e.  isRejected());  if(err) {  throwerr.reason; }  else{  returnresults.  map(e  =>e.  value); } }); }  function  retry(task, maxRetries) {  return  task().  catch(e  =>{  if(  !maxRetries)  return  retry(task, maxRetries  -  1);  throwe; }); }  retry(()  =>  settleAll([  task1(),  task2()]),  5).  then(  console  .log,
  console
  .error);
  Want to know more? Worth to read:

  
       
  •       Promise.mapSeries   
  •       We have a problem with promises  
友荐云推荐




上一篇:欧洲房屋租赁平台 Wimdu 和 9flats 合并,共同抗衡 Airbnb
下一篇:npm scripts 使用指南
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

putihan 发表于 2016-10-11 20:51:14
传说中的沙发???哇卡卡
回复 支持 反对

使用道具 举报

程依铭 发表于 2016-10-11 20:59:55
看帖必转真君子,好贴必顶大丈夫
回复 支持 反对

使用道具 举报

蔡茂超 发表于 2016-10-11 21:33:47
前排,哇咔咔
回复 支持 反对

使用道具 举报

自我催眠 发表于 2016-10-21 19:15:03
我若安好,便是晴天。
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表