当用户注册时,他的个人资料必须从其他网站获取一些值。
我编写了一个返回这些值的函数,但它不会像我想要的那样工作。
以下是代码:
var user = new User(); // to create him in the database
user.userData.someVariable = myFunc(someID);
function myFunc(someID){
.......
Users.findOne({'someVar': someID}, function(err, user){
if(err)
throw err;
if(user)
return user.userData.id; // it doesn't return it, but it has found it
// I can even console.log it, and I see that it exists, but user.userData.someVariable wont be set to user.userData.id
else if(!user) throw err;
}
}
有任何帮助吗?我能做些什么来获得价值吗?谢谢!
答案 0 :(得分:1)
您需要传递回调而不是仅返回值,在您请求值时,请求可能尚未完成。例如:
var user = new User(); // to create him in the database
// Call myFunc and wait for it to finish.
myFunc(someID, function(err, userData){
if (err) throw err;
user.userData.someVariable = userData;
});
function myFunc(someID, callback){
Users.findOne({'someVar': someID}, function(err, user){
if(err)
return callback(err);
if(user)
return callback(null, user.userData.id);
else if(!user) return callback(new Error('User not found!'));
}
}