- MobX Quick Start Guide
- Pavan Podila Michel Weststrate
- 215字
- 2021-08-05 10:34:26
when() with a promise
There is a special version of when(), which takes only one argument (the predicate function), and gives back a promise instead of the disposer function. This is a nice trick where you can skip using the effect function and instead wait for when() to resolve before executing the effect. This is easier to see in code, as shown here:
class Inventory {
/* ... */
async trackAvailability(name) {
// 1. Wait for availability
await when(() => {
const item = this.items.find(x => x.name === name);
return item ? item.quantity > 0 : false;
});
// 2. Execute side-effect
console.log(`${name} is now available`);
}
/* ... */
}
In comment 1, we are waiting for the availability of the item using when() that only takes the predicate function. By using the async-await operators to wait for the promise, we get clean, readable code. Any code that follows the await statement is automatically scheduled to execute after the promise resolves. This is a nicer form of using when() if you prefer not to pass an effect callback.
when() is also very efficient and does not poll the predicate function to check for changes. Instead, it relies on the MobX reactivity system to re-evaluate the predicate function, when the underlying observables change.
推薦閱讀
- 黑客攻防實戰技術完全手冊:掃描、嗅探、入侵與防御
- 智慧城市:大數據、互聯網時代的城市治理(第4版)
- 微商之道
- 面向物聯網的CC2530與傳感器應用開發
- Mastering Machine Learning for Penetration Testing
- 5G承載網網絡規劃與組網設計
- Force.com Development Blueprints
- Wireshark網絡分析就這么簡單
- Mastering TypeScript 3
- 邁向自智網絡時代:IP自動駕駛網絡
- Unity Artificial Intelligence Programming
- TD-LTE無線網絡規劃與設計
- Getting Started with Memcached
- 云工廠:開啟中國制造云時代
- 路由與交換技術