Skip to content

Commit

Permalink
Add promise support to nextTick (#3967)
Browse files Browse the repository at this point in the history
* add promise support to nextTick

* remove test for non-existent nextTick console error

* Update flow annotation for callback

* Revert flow annotation for nextTick callback
  • Loading branch information
chrisvfritz authored and yyx990803 committed Nov 20, 2016
1 parent 048014a commit 8bf2653
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/core/instance/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function initRender (vm: Component) {

export function renderMixin (Vue: Class<Component>) {
Vue.prototype.$nextTick = function (fn: Function) {
nextTick(fn, this)
return nextTick(fn, this)
}

Vue.prototype._render = function (): VNode {
Expand Down
18 changes: 11 additions & 7 deletions src/core/util/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,17 @@ export const nextTick = (function () {
}

return function queueNextTick (cb: Function, ctx?: Object) {
const func = ctx
? function () { cb.call(ctx) }
: cb
callbacks.push(func)
if (!pending) {
pending = true
timerFunc()
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)
}
}
})()
Expand Down
17 changes: 17 additions & 0 deletions test/unit/features/instance/methods-lifecycle.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,22 @@ describe('Instance methods lifecycle', () => {
done()
})
})

if (typeof Promise !== 'undefined') {
it('should be called after DOM update in correct context, when using Promise syntax', done => {
const vm = new Vue({
template: '<div>{{ msg }}</div>',
data: {
msg: 'foo'
}
}).$mount()
vm.msg = 'bar'
vm.$nextTick().then(function (ctx) {
expect(ctx).toBe(vm)
expect(vm.$el.textContent).toBe('bar')
done()
})
})
}
})
})
25 changes: 25 additions & 0 deletions test/unit/modules/util/next-tick.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { nextTick } from 'core/util/env'

describe('nextTick', () => {
it('accepts a callback', done => {
nextTick(done)
})

it('returns undefined when passed a callback', () => {
expect(typeof nextTick(() => {})).toBe('undefined')
})

if (typeof Promise !== 'undefined') {
it('returns a Promise when provided no callback', done => {
nextTick().then(done)
})

it('returns a Promise with a context argument when provided a falsy callback and an object', done => {
const obj = {}
nextTick(undefined, obj).then(ctx => {
expect(ctx).toBe(obj)
done()
})
})
}
})

0 comments on commit 8bf2653

Please sign in to comment.