功能:在下次 DOM 更新循环结束以后执行延迟回调。在修改数据以后当即使用这个方法,获取更新后的 DOM。
默认使用micro, 可是公开了当须要的时候,能够配置强制使用宏任务的方法:在绑定DOM事件的时候,是强制macro
将nextTick的回调函数推入任务栈中。web
nextTick里面的回调函数: function flushCallbacks () { pending = false const copies = callbacks.slice(0) // 清空callbacks 清空栈 callbacks.length = 0 for (let i = 0; i < copies.length; i++) { // 执行每个方法 copies[i]() } }
export function nextTick (cb?: Function, ctx?: Object) { let _resolve // 有可能有多个nextTick被推入到栈里面,因此将这些所有存放在callbacks里面,以后按照顺序执行 callbacks.push(() => { if (cb) { try { cb.call(ctx) } catch (e) { handleError(e, ctx, 'nextTick') } } else if (_resolve) { _resolve(ctx) } }) // pending记录是否开始执行 if (!pending) { pending = true setTimeout(() => flushCallbacks()) } // 若是没有传入参数,直接返回一个Promise if (!cb && typeof Promise !== 'undefined') { return new Promise(resolve => { _resolve = resolve }) } }
在2.4版本以前,nextTick 就是单纯的一个micro tasks,可是micro tasks的优先级过高了,因此扩展了能够将nextTick配置为macro的方法promise
macro tasks实现:浏览器
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { macroTimerFunc = () => { // 强制宏观实现,在浏览器执行完全部之后再去执行回调 setImmediate(flushCallbacks) } } else if (typeof MessageChannel !== 'undefined' && ( isNative(MessageChannel) || MessageChannel.toString() === '[object MessageChannelConstructor]' )) { // 使用messageChannel实现 const channel = new MessageChannel() const port = channel.port2 // 监听flushCallbacks,当port1接受到信息的时候(也就是浏览器执行完全部代码后),再去执行flushCallbacks channel.port1.onmessage = flushCallbacks macroTimerFunc = () => { // port2发送消息1 port.postMessage(1) } } else { /* istanbul ignore next */ // 若是不支持setImmediate和MessageChannel,就用setTimeout,这个会占用不少内存,因此不是最优解法 macroTimerFunc = () => { setTimeout(flushCallbacks, 0) } }
micro tasks实现:bash
if (typeof Promise !== 'undefined' && isNative(Promise)) { // 微观是用Promise是实现的 const p = Promise.resolve() microTimerFunc = () => { p.then(flushCallbacks) // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. // 在有问题的UIWebViews里面,then可能不会彻底的返回,不会执行 ===> 处理方式:“强制”经过添加空计时器刷新微任务队列。( 不明白??) if (isIOS) setTimeout(noop) } } else { // fallback to macro // 若是没有promise就仍是使用宏观 microTimerFunc = macroTimerFunc }
以上两个都实现了优雅降级异步