- 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.
推薦閱讀
- C++黑客編程揭秘與防范
- 物聯網與無線傳感器網絡
- Microsoft Dynamics CRM 2011 Applications(MB2-868) Certification Guide
- OMNeT++與網絡仿真
- Building Web Applications with ArcGIS
- 光纖通信系統與網絡(修訂版)
- Bonita Open Solution 5.x Essentials
- Windows Server 2012 Hyper-V虛擬化管理實踐
- 計算機網絡技術及應用
- 通信十年:擁抱互聯網
- 物聯網頂層設計與關鍵技術
- 5G技術核心與增強:從R15到R17
- TCP/IP基礎(第2版)
- 物聯網的機遇與利用
- Intelligent Mobile Projects with TensorFlow