From b4df52d7b58a1e2f4058829343f6bdf596517c8c Mon Sep 17 00:00:00 2001 From: Raynos Date: Wed, 26 Feb 2020 10:46:44 +0100 Subject: [PATCH] src: Reduce number of unnecessary promises By making `_set` and `async` function instead of a maybe promise returning function we would evaluate every `_set()` in a next tick. This reduces the number of promises in a Tonic app from lots to only per `async render() {}` and per call to `reRender()`. --- index.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/index.js b/index.js index 8a3c7a2a..3f7b6172 100644 --- a/index.js +++ b/index.js @@ -181,7 +181,16 @@ class Tonic extends window.HTMLElement { Tonic._maybePromise(this[e.type](e)) } - async _set (target, render, content = '') { + _drainIterator (target, iterator) { + const p = iterator.next() + return p.then((result) => { + this._set(target, null, result.value) + if (result.done) return + return this._drainIterator(target, iterator) + }) + } + + _set (target, render, content = '') { for (const node of target.querySelectorAll(Tonic._tags)) { if (!node.isTonicComponent) continue if (!node.id || !Tonic._refIds.includes(node.id)) continue @@ -189,19 +198,22 @@ class Tonic extends window.HTMLElement { } if (render instanceof Tonic.AsyncFunction) { - content = await render.call(this) || '' + const promise = render.call(this) || '' + return promise.then((content) => { + return this._apply(target, content) + }) } else if (render instanceof Tonic.AsyncFunctionGenerator) { const itr = render.call(this) - while (true) { - const { value, done } = await itr.next() - this._set(target, null, value) - if (done) break - } - return + return this._drainIterator(target, itr) } else if (render instanceof Function) { content = render.call(this) || '' + return this._apply(target, content) } + return this._apply(target, content) + } + + _apply (target, content) { if (content && content.isTonicRaw) { content = content.rawText }