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

  • 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.
主站蜘蛛池模板: 长垣县| 宁津县| 沙湾县| 且末县| 莱阳市| 曲周县| 海伦市| 临澧县| 黔江区| 彭州市| 金阳县| 扶沟县| 登封市| 河南省| 策勒县| 博爱县| 汤阴县| 内丘县| 田林县| 嘉峪关市| 沈丘县| 黄大仙区| 陆丰市| 红河县| 临西县| 镇赉县| 伊通| 调兵山市| 林周县| 兴业县| 思茅市| 永胜县| 彩票| 萨迦县| 峨眉山市| 康定县| 防城港市| 当阳市| 隆德县| 广德县| 巨鹿县|