You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让这段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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 10:36:43