Pages

Friday, August 5, 2016

Learning Meteor.js [Part 44]: Return results from methods 'synchronously' using Fibers

The application is almost finished. To recap: users can create ingredients, then use those ingredients to create recipes and then use both ingredients and recipes to create orders. The final feature is to build the shopping list for the order so users can head out to the super market.

There will be a server method that, given an order id, will return all ingredients used across all recipes grouped by category.
export const getShoppingList = new ValidatedMethod({
    name: 'order.getShoppingList',
    validate: new SimpleSchema({
        orderId: { type: String }
    }).validator({ clean: true}),
    run({ orderId }) {
        if (Meteor.isClient) {
            return;
        }

        var meals = Meals.find({ orderId : orderId }).fetch();

        return buildShoppingListFromMeals(meals);
    }
});

For brevity, I won't include the whole implementation but you can see the full code here. The important thing to notice is the lack of callbacks when querying mongodb. And you can imagine that to build the result we need to make many queries to the database, for example, fetch all the recipes used and fetch all the ingredients used.

This is possible by meteor's use of Fibers. It enables to write code that looks synchronous, similar to .NET async/await. You can read more about it in 'Fibers, Event Loop and Meteor'.

You can see the screen capture below for a sample of how the experience looks like. You can also visit the live demo or view the soure code.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.