我注意到虽然服务器方法运行良好,但回调函数永远不会被执行。同样来自Meteor文档,我知道当抛出Meteor.Error时它会通知客户端,但我也看不到它也能正常工作。我做了一些根本错误的事情吗?
if (Meteor.isCordova) {
getContacts(function (contacts) {
$meteor.call('createContacts', contacts, function(err){
alert("in create contacts callback");
if(err && err.error === "not-logged-in"){
alert("error due to not-logged-in");
$ionicPopup.alert({
title: err.reason || "User not logged in",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
else if(err && err.error === "contacts-exists"){
$ionicPopup.alert({
title: err.reason || "Connections already exists",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
$meteor.call('createConnections');
});
});
}
function getContacts(success, error) {
function onSuccess(contacts) {
success && success(contacts);
};
var options = {};
options.multiple = true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, error, options);
}
createContacts: function (contacts, callback) {
if (!this.userId) {
throw new Meteor.Error('not-logged-in',
'Must be logged in to update contacts')
}
var userId = this.userId, exist = Contacts.findOne({userId: userId});
log.debug("Is contacts for userId %s exist in database ? %s", userId, !! exist);
if (!exist) {
Contacts.insert({'userId': userId, 'contacts': contacts}, function () {
callback && callback();
});
} else {
log.debug("Contacts for user exists so throwing exception as contacts-exists");
var meteorErr = new Meteor.Error('contacts-exists', "Contacts are already exist");
callback && callback(meteorErr);
}
},
答案 0 :(得分:0)
这些回调是异步的。您的服务器端方法不应该调用回调函数,也不应该将其作为参数。
您将回调作为Meteor.call('createContacts')
的最后一个参数传递是正确的,但不能由createContacts
的接收器决定何时应该调用该回调。简单来说,从客户的角度来看,服务器的工作就是返回“OK”或“错误”信号。
删除方法定义中(在服务器上)对回调的任何引用,并期望客户端在服务器响应时执行该回调。
试试这个:
服务器强>
createContacts: function (contacts) {
if (!this.userId) {
throw new Meteor.Error('not-logged-in',
'Must be logged in to update contacts');
}
var userId = this.userId;
var exist = Contacts.findOne({userId: userId});
log.debug("Is contacts for userId %s exist in database ? %s", userId, !! exist);
if (!exist) {
Contacts.insert({'userId': userId, 'contacts': contacts});
} else {
log.debug("Contacts for user exists so throwing exception as contacts-exists");
throw new Meteor.Error('contacts-exists', "Contacts are already exist");
}
},
<强>客户端强>
$meteor.call('createContacts', contacts, function(err){
alert("in create contacts callback");
if(err && err.error === "not-logged-in"){
alert("error due to not-logged-in");
$ionicPopup.alert({
title: err.reason || "User not logged in",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
else if(err && err.error === "contacts-exists"){
$ionicPopup.alert({
title: err.reason || "Connections already exists",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
$meteor.call('createConnections');
});
答案 1 :(得分:0)