作家
登录

用Async函数简化异步代码

作者: 来源: 2017-04-19 11:20:13 阅读 我要评论

function doAsyncOp() { 
  •  
  •   // the next line will kill execution 
  •  
  •   throw new Error("something is bad"); 
  •  
  •   return new Promise(function(resolve, reject) { 
  •  
  •     if (somethingIsBad) { 
  •  
  •       throw new Error("something is bad"); 
  •  
  •     } 
  •  
  •     resolve("nothing is bad"); 
  •  
  •   }); 
  •  
  •  
  •   
  •  
  • // assume `doAsyncOp` does not have the killing error 
  •  
  • function x() { 
  •  
  •   var val = doAsyncOp().then(function() { 
  •  
  •     // this one will work just fine 
  •  
  •     throw new Error("I just think an error should be here"); 
  •  
  •   }); 
  •  
  •   // this one will kill execution 
  •  
  •   throw new Error("The more errors, the merrier"); 
  •  
  •   return val; 
  •  
  •  
  • 在 async 函数的 Promise 中抛掉足误就不会产生有关范围的问题——你可以在 async 函数中随时随地抛掉足误,它总会被 Promise 抓住:

    1. async function doAsyncOp() { 
    2.  
    3.   // the next line is fine 
    4.  
    5.   throw new Error("something is bad"); 
    6.  
    7.   if (somethingIsBad) { 
    8.  
    9.     // this one is good too 
    10.  
    11.     throw new Error("something is bad"); 
    12.  
    13.   } 
    14.  
    15.   return "nothing is bad"
    16.  
    17. }  
    18.  
    19.   
    20.  
    21. // assume `doAsyncOp` does 

        推荐阅读

        一文看懂数据可视化:从编程工具到可视化表现方式

      说到可视化,就不得不说一下大年夜数据,毕竟可视化是解决大年夜数据的一种高效的手段,而如今人人都在谈论大年夜数据,大年夜数据 ≠ 稀有据 ≠ 数据量大年夜, 离谱的是,如今就连>>>详细阅读


      本文标题:用Async函数简化异步代码

      地址:http://www.17bianji.com/lsqh/34848.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)