聚合物:何时使用异步? [英] Polymer: when to use async?

查看:76
本文介绍了聚合物:何时使用异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async方法在聚合物中的用途是什么?我什么时候应该使用它?

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

现在我正在使用它,例如 hm-this-bug-is-kinda-weird-beynchronous-will-fix-it-yep-id-did-yey .当我出现某些计时错误时,我撒了async,这对我的代码没有任何信心.

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.

推荐答案

根据您使用的是Polymer 0.5还是1.0,答案略有不同.在1.0中,更多的操作是同步的,因此您可能看不到异步的需求(也

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).

让我们从0.5开始.大多数情况与属性更改的影响有关.观察数据绑定或观察者中使用的属性的更改.当您更改其中之一时 属性,该更改的任何副作用均异步发生,并带有微任务计时.这意味着工作发生在当前事件处理程序返回之后,但在之前被处理下一个事件.

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>

假设我有以下代码:

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

这是异步咬住你的地方.如果要更新绑定的数据,则需要给数据绑定系统一个工作的机会.如果将console.log语句移到异步中,以便稍后执行,则会得到您期望的响应:

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"
});

大多数时候,您不需要戳数据绑定的DOM元素.但是,如果您这样做或正在等待观察者的副作用,则可能需要异步.

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.

在Polymer 1.0中,数据绑定和单属性观察器是同步的.多属性观察者和某些DOM操作是异步的.

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

(尽管API与Jav​​aScript不同,但有关事件循环的Dart这篇文章是我发现的描述事件循环和微任务队列的最佳文章:

(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/)

这篇关于聚合物:何时使用异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆