Waiting for meteor collection to finish before next step

前端 未结 3 859
谎友^
谎友^ 2020-12-09 11:30

I have a Meteor template that should be displaying some data.

Template.svg_template.rendered = function () {
  dataset_collection = Pushups.find({},{fields         


        
3条回答
  •  感情败类
    2020-12-09 12:11

    This is one of those problems that I really wish the basic meteor documentation addressed directly. It's confusing because:

    1. You did the correct thing according to the API.
    2. You get errors for Deps which doesn't point you to the root issue.

    So as you have already figured out, your data isn't ready when the template gets rendered. What's the easiest solution? Assume that the data may not be ready. The examples do a lot of this. From leaderboard.js:

    Template.leaderboard.selected_name = function () {
        var player = Players.findOne(Session.get("selected_player"));
        return player && player.name;
    };
    

    Only if player is actually found, will player.name be accessed. In coffeescript you can use soaks to accomplish the same thing.

    saimeunt's suggestion of iron-router's waitOn is good for this particular use case, but be aware you are very likely to run into situations in your app where the data just doesn't exist in the database, or the property you want doesn't exist on the fetched object.

    The unfortunate reality is that a bit of defensive programming is necessary in many of these cases.

提交回复
热议问题