From f242e119fab42e2f80dfea5fc9e0eaffd1587af7 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 20 Nov 2016 12:03:24 -0500 Subject: [PATCH] fix nextTick Promise implementation for polyfills --- src/core/util/env.js | 26 ++++++++++--------- .../instance/methods-lifecycle.spec.js | 2 +- test/unit/index.js | 2 ++ test/unit/modules/util/next-tick.spec.js | 11 +++++++- 4 files changed, 27 insertions(+), 14 deletions(-) diff --git a/src/core/util/env.js b/src/core/util/env.js index dd713546..f4230dae 100644 --- a/src/core/util/env.js +++ b/src/core/util/env.js @@ -86,18 +86,20 @@ export const nextTick = (function () { } } - return function queueNextTick (cb: Function, ctx?: Object) { - if (cb) { - var func = ctx - ? function () { cb.call(ctx) } - : cb - callbacks.push(func) - if (!pending) { - pending = true - timerFunc() - } - } else if (typeof Promise !== 'undefined') { - return Promise.resolve(ctx) + return function queueNextTick (cb?: Function, ctx?: Object) { + let _resolve + callbacks.push(() => { + if (cb) cb.call(ctx) + if (_resolve) _resolve(ctx) + }) + if (!pending) { + pending = true + timerFunc() + } + if (!cb && typeof Promise !== 'undefined') { + return new Promise(resolve => { + _resolve = resolve + }) } } })() diff --git a/test/unit/features/instance/methods-lifecycle.spec.js b/test/unit/features/instance/methods-lifecycle.spec.js index 865d67ac..71525be2 100644 --- a/test/unit/features/instance/methods-lifecycle.spec.js +++ b/test/unit/features/instance/methods-lifecycle.spec.js @@ -119,7 +119,7 @@ describe('Instance methods lifecycle', () => { } }).$mount() vm.msg = 'bar' - vm.$nextTick().then(function (ctx) { + vm.$nextTick().then(ctx => { expect(ctx).toBe(vm) expect(vm.$el.textContent).toBe('bar') done() diff --git a/test/unit/index.js b/test/unit/index.js index e4184dca..35df6c94 100644 --- a/test/unit/index.js +++ b/test/unit/index.js @@ -1,3 +1,5 @@ +require('es6-promise/auto') + // import all helpers const helpersContext = require.context('../helpers', true) helpersContext.keys().forEach(helpersContext) diff --git a/test/unit/modules/util/next-tick.spec.js b/test/unit/modules/util/next-tick.spec.js index fc78931b..92afa774 100644 --- a/test/unit/modules/util/next-tick.spec.js +++ b/test/unit/modules/util/next-tick.spec.js @@ -6,7 +6,7 @@ describe('nextTick', () => { }) it('returns undefined when passed a callback', () => { - expect(typeof nextTick(() => {})).toBe('undefined') + expect(nextTick(() => {})).toBeUndefined() }) if (typeof Promise !== 'undefined') { @@ -21,5 +21,14 @@ describe('nextTick', () => { done() }) }) + + it('returned Promise should resolve correctly vs callback', done => { + const spy = jasmine.createSpy() + nextTick(spy) + nextTick().then(() => { + expect(spy).toHaveBeenCalled() + done() + }) + }) } })