如何让这段JS样式加载监听的Promise代码写法更优雅?
实现优化方案
你原本的实现逻辑完全可行,只是可以去掉冗余的中间变量,写法更精简:
var genStyle = () => { const instance = {} setTimeout(() => { instance.onload && instance.onload() }, Math.random() * 3000) return instance } var a = genStyle() var b = genStyle() var c = genStyle() /* implementation start */ const wrap = target => new Promise(resolve => target.onload = resolve) Promise.all([ wrap(a), wrap(b), wrap(c) ]).then(() => console.log('all done')) /* implementation end */
如果样式实例数量不多,甚至不需要单独抽包装函数,直接在Promise.all里写即可:
Promise.all([ new Promise(res => a.onload = res), new Promise(res => b.onload = res), new Promise(res => c.onload = res) ]).then(() => console.log('all done'))
如果后续要新增更多样式实例,可以把实例统一放到数组里批量处理,不需要逐个写包装逻辑:
const styleList = [a, b, c] Promise.all(styleList.map(item => new Promise(resolve => item.onload = resolve))) .then(() => console.log('all done'))
实现说明
- Promise构造器的executor函数是同步执行的,给实例绑定
onload的操作会立刻完成,不会错过回调触发时机 onload触发时不需要接收额外参数,直接把resolve作为回调传入即可,不需要额外套一层中转函数- 删掉了原实现里无意义的
tick临时变量,逻辑链路更短
内容的提问来源于stack exchange,提问作者Guirotar Lionad
相关产品推荐
相关产品推荐

