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

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.
主站蜘蛛池模板: 绥化市| 大丰市| 宣城市| 玛纳斯县| 四子王旗| 东兴市| 曲阜市| 蕲春县| 庆元县| 平定县| 上思县| 渭源县| 夏邑县| 绥中县| 临猗县| 连州市| 宁晋县| 博罗县| 扬中市| 兴海县| 志丹县| 阳城县| 衡东县| 镇宁| 泰州市| 蓬安县| 平陆县| 奉贤区| 新邵县| 古丈县| 上林县| 竹溪县| 南乐县| 淮滨县| 古田县| 青铜峡市| 长垣县| 贞丰县| 吴桥县| 肥东县| 定襄县|