Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer: when to use async?

Tags:

polymer

What's the purpose of async method in polymer? When should I use it?

Right now I'm using it like hm-this-bug-is-kinda-weird-maybe-async-will-fix-it-yep-id-did-yey. It does not give me any confidence in my code as I'm sprinkling async just when some timing bug shows up.

like image 710
user1463822 Avatar asked May 06 '15 15:05

user1463822


1 Answers

The answer is slightly different here depending on whether you're using Polymer 0.5 or 1.0. In 1.0, more operations are synchronous, so you may not see quite as much need for async (also, the async method works slightly differently in 1.0).

Let's start with 0.5. Most of the cases have to do with the effects of changing properties. Properties used in data bindings or observers are observed for changes. When you change one of these properties, any side-effects of that change take place asynchronously, with microtask timing. That means that the work happens after the current event handler returns, but before the next event is processed.

In other words, if I have a data binding like this:

<div id="output">{{someProperty}}</div>

Suppose I have the following code:

this.someProperty = "New Value";
console.log(this.$.output.textContent); // logs "Old Value"

This is where the asynchrony bites you. If you want the bound data to be updated, you need to give the data binding system a chance to work. If you move that console.log statement into an async, so it's executed at a later time, you get the response you expect:

this.async(function() {
  console.log(this.$.output.textContent); // logs "New Value"
});

Most of the time, you don't need to poke at data bound DOM elements. But in the event that you do, or that you're waiting on the side effect of an observer, you probably want an async.

In Polymer 1.0, data binding and single-property observers are synchronous. Multi-property observers and some DOM operations are async.

(While the APIs are different from JavaScript, this Dart article about the event loop is the best one I've found to describe the event loop and microtask queue: https://www.dartlang.org/articles/event-loop/)

like image 64
DocDude Avatar answered Oct 10 '22 00:10

DocDude