将使用回调函数作为参数的函数改造为返回 Promise 的一个具体例子

我开发了一个函数 loadScript,可以动态加载指定的本地 JavaScript 文件。源代码如下:
然后开发一个函数 promisify
,可以将任意传递进来的函数 f,改造成返回参数类型为 Promise 的新函数。
具体的消费方式:
其中 1.js 的内容:
下面我们进行单步调试。
待改造的 loadScript,包含两个函数:

调用 promisify,返回一个新的函数。

这个新的函数包含一个闭包 f,可以调用没有 promisify 之前的旧函数。

使用这个新函数加载 1.js:

进入这个新函数内部,执行 executor body:

在函数体内部可以随时访问 callback:

我们期望 script onload 事件发生时,会使用 Promise 自带的 resolve 和 reject 传递参数,因此自己编写了一个 callback 函数,在这个 callback 函数里,使用 Promise 的 resolve 投递结果。
并且期望将这个 callback 函数,传递给原始的 loadScript 函数内部。我们通过 function
原型链上的 call 函数,就达到了调用原始的 loadScript 函数的目的。

并且此时的 callback 函数,确实是我们在 promisify 函数内编写的使用 Promise resolve 传递结果的函数。

稍后,script.onload 异步触发:

通过 resolve,将加载完毕的 script 元素,传递给 promise 对象通过 then 注册的回调函数。


版权声明: 本文为 InfoQ 作者【Jerry Wang】的原创文章。
原文链接:【http://xie.infoq.cn/article/50f99e428cdb4418862690781】。文章转载请联系作者。
评论