官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 大理市| 陆河县| 连城县| 洛南县| 广汉市| 民县| 分宜县| 大同县| 合江县| 长海县| 台北市| 柳江县| 中西区| 丰城市| 额敏县| 安达市| 汽车| 清徐县| 庆云县| 吉林市| 原阳县| 牟定县| 天峻县| 屯门区| 莎车县| 凌海市| 深州市| 赞皇县| 闸北区| 左权县| 喀什市| 虹口区| 时尚| 洛扎县| 旬邑县| 甘德县| 宜章县| 栾城县| 建始县| 司法| 湘阴县|