javascript学习指南之回调问题.docVIP

  • 7
  • 0
  • 约4.1千字
  • 约 8页
  • 2019-04-05 发布于广东
  • 举报
javascript学习指南之回调问题 回调函数被认为是一种高级函数,一种被作为参数传 递给另一个函数(在这称作otherFunction)的高级函数, 回调函数会在otherFunction内被调用(或执行)。回调函 数的本质是一种模式(一种解决常见问题的模式),因此回 调函数也被称为回调模式。 回调地狱 对JavaScript程序员来说,处理回调是家常,但是处 理层次过深的回调就没有那么美好了,下面的示例代码片 段用了三层回调,再补脑一下更多层的场景,简直是酸爽 这就是传说中的回调地狱。 get Directories (function (d irs) { nbsp :getFiles (d irs[0], func tion(files) { nbsp;nbs p:getConten t (files [0], function(fi le,content) { nbsp;nbs p:nbsp:cons ole. logC fi lename:’,fi le); nbsp; nbsp; nbsp ;c onsole. log (content); nb sp;nbsp;}); nbsp;}): }); functiong etDirectori es (callback ) { nbsp; se tTimeout (fu notion() { nbsp; callba ck([’ /home/ben’ ]); nbsp 1000); } functionge tFiles (dir, callback) { nbsp; setTi meout (funct ion() { nbs p;nbsp;call back ([dir+, /testl. txt’,dir+’ /test 2. txt’ ]); nb sp;},1000) functiong etContent (f ile, callbac k) { nbsp; s etTimeout (f unction() { nbsp:nbsp:callback(fi le,’ content ’); nbsp;},1 000) 解决方案 生态圈中有很多异步解决方案可以处理回调地狱的问 题,比如bluebi rd、Q等,本文重点介绍ECMAScript 6/7 规范中对异步编程的支持。 ES6Prom ise Promis e是一■种异步编程的解决方案,是解决回调地 狱问题的利器。 Prom ise在JavaScr ipt生态圈被主流接受是在XX年 Dojo框架增加了 dojo. Def erred的功能。随着 dojo. Deferr ed 的流行,在 XX 年 K risZyp 提出了 Co mmonJSPromi ses/A规范。随后生态圈中出现了大量Pro mise实现包括Q. j s、FuturesJS等。当然Promise之所有 这么流行很大程度上是由于jQuery的存在,只是j Query 并不完全遵守Commo nJSPromises /A规范。随后正如大家 看到的,ES6规范包含了 Promisee MDN中对Promise是这样描述的: Pro mise对象是一个返回值的代理,这个返回值在 promise对象创建时未必已知。它允许你为异步操作的成功 或失败指定处理方法。这使得异步方法可以像同步方法那 样返回值:异步方法会返回一个包含了原返回值的 以下的代码是「回调地狱」一节中的示例通过P romise实现,看上去代码也不是很简洁,但是比起传统的 层级回调有明显改善,代码可维护性和可读性更强。 ge tDirectorie s (). then (fu notion (dirs ) { nbsp;re turngetFile s(dirs[0]): }). then(f unction(fil es) { nbsp:returngetCo ntent (files [0]); }). t hen (functio n (val) { nb sp; console, log (’ f ilena me: ’,val. f i le); nbsp;console, log (val. conten t); }); fun ctiongetDir ectories () { nbsp;retu rnnewPromis e(function ( resolve, rej ect) { nbsp :nbsp;setTi meout (funct ion() { nbs p; nbsp; reso lve ([’ /home /ben’ ]); nbs p;nbsp;}, 10 00): nbsp;}): } funct io ngetFiles (d ir) {

文档评论(0)

1亿VIP精品文档

相关文档