流星 - 没有"findOne"功能的回调

Sw0*_*0ut 6 mongodb meteor

我正在研究一个Meteor项目,我必须说这根本不容易,特别是对于一件事:回调!

一切都是异步的,所以我想知道如何从我的mongodb获得结果.

var user = Meteor.users.findOne({username: "john"});
return (user); // sometimes returns "undefined"
Run Code Online (Sandbox Code Playgroud)

...

var user = Meteor.users.findOne({username: "john"});
if (user)                    // so ok, I check if it exists!
    return (user);           // Cool, I got my user!
return ();                   // Ok and what should I return here? I want my user!
Run Code Online (Sandbox Code Playgroud)

我不想变脏,像setTimeout一样放在各处.有人有解决方案吗?


编辑: 我注意到在router.js中使用console.log,我的数据被返回4次.带有未定义值的2次,带有预期值的2次.在视图中,它仍然未定义.为什么路由器在此路由中传递了4次?它是否显示路由器中返回值的第一个结果?

如果find()没有找到任何内容,我应该返回什么?


编辑2:这是一些需要理解的代码.

this.route('profilePage', {
    path: 'profil/:_id?',
    waitOn: function() {
        return [
        Meteor.subscribe('article', { prop: this.params._id}), // id can be id or username
        Meteor.subscribe('article', { userId: this.params._id}), // id can be id or username
        Meteor.subscribe('params'),
        Meteor.subscribe('profil', (this.params._id ? this.params._id : Meteor.userId()))
        ];
    },
    data: function() {
        if (this.params._id) {
            var user = Meteor.users.findOne(this.params._id);
            if (!user)
                user = Meteor.users.findOne({username: this.params._id});
            console.log(user);
            return user;
        }
        else if (Meteor.userId())
            return Meteor.user();
        else
            Router.go("userCreate");
    }
});
Run Code Online (Sandbox Code Playgroud)

我在控制台上看到了这个:http: //puu.sh/debdJ/69419911f7.png

(以下文字版)

undefined
undefined
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
Run Code Online (Sandbox Code Playgroud)

Már*_*rio 4

findOne(yourId)是一种同步方法,相当于find({ _id: yourId}, callback). 不同之处在于find()允许您定义回调。如果您不传递回调find()到此方法将是同步的。

检查wrapAsync: http: //docs.meteor.com/#/full/meteor_wrapasyncsync它允许您以带有操作的样式 进行编码async

EventedMind 免费课程:https ://www.eventedmind.com/feed/meteor-meteor-wrapasync