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

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.
主站蜘蛛池模板: 靖宇县| 大悟县| 霍州市| 南京市| 威宁| 金川县| 双辽市| 巴青县| 万安县| 宝鸡市| 黎川县| 永昌县| 汶上县| 巴青县| 巴楚县| 穆棱市| 松潘县| 精河县| 台中县| 康平县| 平潭县| 建德市| 泗水县| 二连浩特市| 田东县| 上林县| 曲阜市| 郴州市| 广水市| 沧州市| 肃宁县| 府谷县| 礼泉县| 西平县| 九江市| 渭源县| 新蔡县| 敦化市| 祁连县| 泉州市| 中阳县|