V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
7Brant
V2EX  ›  分享创造

写了一个名叫 Promising 的 Promises/A+ 规范实现(以及配套测试方法)

  •  
  •   7Brant · 2017-08-21 13:01:36 +08:00 · 1757 次点击
    这是一个创建于 2433 天前的主题,其中的信息可能已经有所发展或是发生改变。

    起了一个好玩的名字:Promising,主要是想深入学习一下 Promise 到底是怎么回事,最后发现照着规范的条条框框就能差不多直译出来。

    提供的 API 有:

    • Promising()
    • Promising.resolve()
    • Promising.reject()
    • Promising.prototype.then()
    • Promising.prototype.catch()

    没有提供的 API 有:

    • Promising.all()
    • Promising.race()

    额外提供了两个辅助测试的方法 mayBeResolvedmayBeRejected,能配合 Mocha 使用:

    // test.js
    
    const { mayBeResolved, mayBeRejected } = require('./helper')
    
    describe('testing static methods: ', () => {
      it('should be resolved', () => {
        mayBeResolved(Promising.resolve(42)).then((value) => {
          expect(value).to.equal(42)
        })
      })
      it('should be rejected', () => {
        mayBeRejected(Promising.reject('oops')).catch(reason => {
          expect(reason).to.equal('oops')
        })
      })
    })
    

    最后附上 Repo 地址:Promising

    2 条回复    2017-08-21 21:29:32 +08:00
    8qwe24657913
        1
    8qwe24657913  
       2017-08-21 18:09:00 +08:00   ❤️ 1
    setTimeout 是 task,Promise 是 microtask,建议参考 es6-promise 用 MutationObserver https://github.com/stefanpenner/es6-promise/blob/master/lib/es6-promise/asap.js
    7Brant
        2
    7Brant  
    OP
       2017-08-21 21:29:32 +08:00
    @8qwe24657913 谢谢指出,确实应该是 microtask
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2596 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:20 · PVG 23:20 · LAX 08:20 · JFK 11:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.