- 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.
推薦閱讀
- 智慧城市:大數(shù)據(jù)、互聯(lián)網(wǎng)時代的城市治理(第4版)
- 網(wǎng)絡(luò)協(xié)議工程
- FreeSWITCH 1.2
- Twilio Cookbook
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- 智慧城市中的移動互聯(lián)網(wǎng)技術(shù)
- 互聯(lián)網(wǎng)安全的40個智慧洞見:2014年中國互聯(lián)網(wǎng)安全大會文集
- The Kubernetes Workshop
- 搶占下一個智能風口:移動物聯(lián)網(wǎng)
- Getting Started with Memcached
- 設(shè)備監(jiān)控技術(shù)詳解
- SEO攻略:搜索引擎優(yōu)化策略與實戰(zhàn)案例詳解
- 新IP:面向泛在全場景的未來數(shù)據(jù)網(wǎng)絡(luò)
- 黑客心理學:社會工程學原理
- 加密與解密實戰(zhàn)全攻略