简体   繁体   English

流星-onCreateUser Ajax回调

[英]Meteor - onCreateUser Ajax callback

In the Accounts.onCreateUser function of Meteor, I would like to make an ajax request to get the user details from the Twitter API. 在Meteor的Accounts.onCreateUser函数中,我想发出一个ajax请求以从Twitter API获取用户详细信息。 While the actual Twitter call works fine and retrieves the expected data, I am unable to return this as the ajax call is done asynchronously. 尽管实际的Twitter调用工作正常并且可以检索预期的数据,但由于ajax调用是异步完成的,因此我无法返回此数据。 Here is where I'm at: 这是我的位置:

Accounts.onCreateUser(function(options, user) {

    user.profile = "";
    Twitter.get.userinfo({ screen_name: 'username'}, function(data) {
        user.profile = data;
    });

    return user;

});

As Accounts.onCraeteUser is part of Meteor, I'm not sure what the best option is to return the data pulled from the request. 由于Accounts.onCraeteUser是Meteor的一部分,因此我不确定最好的选择是返回从请求中提取的数据。 Thanks in advance. 提前致谢。

Wrap your call into an async wrapper (that converts it into a synchronous function). 将您的调用包装到异步包装器中(该包装器将其转换为同步函数)。

Be aware this only works if the callback is something like function(err, data) . 请注意,这仅在回调类似于function(err, data)

In the code above you've used function(data) . 在上面的代码中,您已经使用过function(data) I'm not too sure of any Twitter apis that do it this way. 我不太确定会以这种方式执行此操作的任何Twitter API。 If you could check it is actually function(err,data) and if not I'll try edit the answer with something else 如果您可以检查它实际上是function(err,data) ,否则请尝试用其他方法编辑答案

var getUserInfo = Meteor._wrapAsync(Twitter.get.userinfo.bind(Twitter.get));

user.profile = getUserInfo({screen_name: 'username'});

So what Meteor._wrapAsync does is it takes the function you give it and makes it synchronous on the server side. 所以Meteor._wrapAsync是采用您提供的功能并使它在服务器端同步。 As soon as a result is returned in the callback, the second param (data) is returned. 在回调中返回结果后,将立即返回第二个参数(数据)。

If the first param, err , is returned it will throw it as an error. 如果返回第一个参数err ,它将作为错误抛出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM