Skip to content

Commit

Permalink
src: Reduce number of unnecessary promises
Browse files Browse the repository at this point in the history
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()`.
  • Loading branch information
Raynos committed Feb 26, 2020
1 parent a26450c commit b4df52d
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,27 +181,39 @@ 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
Tonic._states[node.id] = node.getState()
}

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
}
Expand Down

0 comments on commit b4df52d

Please sign in to comment.