从Promise的Then说起
Promise 之所以让代码更人性化,是因为它把原本跳来跳去的 callback 流程变成了线性的 then 链,逻辑更清晰可读。在此基础上,Abstract-fence 2.0 进一步把 function 分解为多个 task,通过依赖数组和 then 组合编排异步流程,并用依赖注入传递参数,让执行顺序更加直观。
但作者在使用 Promise.all 时遇到一个奇怪问题:只要定义了 Array.prototype.then,Promise.all([p]).then(...) 里的回调就永远不会执行。沿着 Promise A+ 规范往下看,then 需要返回新 Promise,并对回调返回值 x 做解析——若 x 是 thenable(有 then 方法的对象或函数)就执行它的 then,否则直接作为值满足 promise2。而规范并未定义 Promise.all 的行为,于是作者去查 bluebird 的实现:Promise.all 只是 new PromiseArray(promises).promise(),真正的逻辑在 promise_array 的 _init 中,它先用 tryConvertToPromise 尝试把参数转成 Promise,成功后按 pending/fulfilled/rejected 分别处理,最后才用 util.asArray 校验数组。结论就清楚了:一旦数组被赋予 then 方法,它就成了 thenable,会被 tryConvertToPromise 转成 Promise;而这个自定义 then 并未实现 Promise 规范,导致 Promise 对象永远处于 pending,Promise.all 也就永远无法 fulfilled。