wrapAsync + method + session - asynchronous

i'm having issues with wrapAsync + method + sessions.
How do I implement the WrapAsync correctly?
I want, in a template to know if the user has at least one item created by him. And then define whether or not he can create another item.
Now i'm getting this error:
W20141013-15:04:43.237(-3)? (STDERR) Error: Can't wait without a fiber
But, I could not find Fiber at Documentation. And for implementing this, is it really necessary?
 
On the client side I want something like:
//pagina.js
Template.pagina.helpers{
userHasItem: return Session.get('userHasItem');
}
//pagina.js
Meteor.call('userHasItem', Meteor.userId(), function (error,result) {
Session.set('userHasItem', result);
});
//at server side:
if(Meteor.isServer){
Meteor.startup(function () {
var userHasItemAsync = function (userId) {
setTimeout(function () {
if (Items.findOne({'userId': userId})) {
return true;
} else {
return false;
}
}, 4000);
};
Meteor.methods({
userHasItem: function(userId) {
var userHasItemSync = Meteor.wrapAsync(userHasItemAsync),
result;
try {
userHasItemSync(userId);
console.log(result);
return result;
}catch (e) {
console.log('erreur', e.message);
throw new Meteor.Error(500, e);
}
},
}
});
}

Can't get your error to reproduce based on the existing code.
Still, userHasItemAsync is not available because you've defined it locally in the Meteor.startup function. But the error you should get in this case is userHasItemAsync is undefined.
Also the code you've entered here has multiple errors (i guess you typed it in not copy / pasted from your project): template instead of Template, Template it's defined outside of isClient (probably it's in a file available for the client) etc. Because of that it's hard to reproduce your exact case.

There is no need to call a server method to see if the item exists (assuming you have set up the proper publications/subscriptions), nor any need to call wrapAsync. In fact, what you want to achieve doesn't even require a session. All of the code can be ultimately distilled to this:
Template.pagina.helpers{
userHasItem: return Items.find({ userId: Meteor.userId() }).count() > 0;
}
The cursor returned by Items.find is reactive in itself, so there is no need for using a Session.

Related

Meteor wrapAsync

I'm trying to implement the following scenario:
1. Client calls a meteor-method.
2. Inside the meteor-method i make an HTTP-Post to a different server.
3. When the HTTP-Call is responded, the meteor method should return true and in the case an error occurs it should return false.
Here is what my meteor method looks like:
uploadUserImage: function(data_url,userid) {
asyncfnc =function(data,uid){
HTTP.post("http://localhost:2000/upload", {
data: {
"data_url": data,
"user_id": uid
}
},function(err,res){
console.log(res);
if (err){
console.log("error");
throw new Error(err.message);
}
else{
console.log("return true");
return true;
}
});
};
var waitForResult = Meteor.wrapAsync(asyncfnc);
var result = waitForResult(data_url,userid);
return result;
}
The HTTP-Call works and I also get into the Callback of the HTTP.post-function.
But on the clientside where I called the meteor-method i don't get into my callback-function. It looks like this:
Meteor.call("uploadUserImage",data_url,Session.get("newUserID"),function (err, res) {
if(err){
console.log(err);
} else {
console.log('response: ', res);
}
});
What am I doing wrong? Why is my meteor-method not returning anything?
Is everything correct with my Meteor.wrapAsync()?
Thanks for your help!
I found a solution, which does not require Meteor.wrapAsync().
var url = "http://localhost:2000/upload";
//synchronous GET
var result = Meteor.http.post(url,{
data: {
"title": "i want to upload a picture",
"data_url": data_url,
"user_id": userid
},timeout:30000});
if(result.statusCode==200) {
console.log(result);
console.log("response received.");
return result;
} else {
console.log("Response issue: ", result.statusCode);
var errorJson = JSON.parse(result.content);
throw new Meteor.Error(result.statusCode, errorJson.error);
}
This makes the HTTP-Post-Call synchronous, so there is no need to wrap async.
You are asking too much in this situation.
Meteor methods can be called synchronously, but it's not advisable if the method is doing a remote call like this.
My feeling is that you are hanging on to a procedural programming model where you want a synchronous result to 1) a call to your server, and 2) a request sent to another remote server. And you want to get a return value from your call. It doesn't work like that.
Meteor protects you to a large degree from dealing with asynchronicity, but sometimes you have to accept that a little more work is required to deal with it correctly.
So my recommendation is to use callbacks for notification.

meteorjs get data returned from server callback

In meteor im trying to insert a new document by making a Meteor.call from the client. Everything is working ok, except that I want to return the id of create document to the client, so that i can redirect to the proper url.
I have something similar to this (client):
Meteor.call('scenarioCreate', scenarioObj, function(err, response) {
if(err) {
console.warn(err);
return;
}
console.info(response);
});
On server:
Meteor.methods({
'scenarioCreate': function(scenarioObj) {
Scenarios.insert( scenarioObj, function(err, id) {
console.info("new id: "+id);
if (err) {
console.warn(err);
throw new Meteor.Error(404, 'Something went wrong');
}
return id;
});
}
});
From the server side i get the console log "new id: DDaq4aWsGf3fxG7RP", but I should get that same value on the client on the "response" value, but I always get undefined.
Can anybody explain to me why or what I am doing wrong.
Meteor.methods doesn't wait for your callback. Try this:
On server:
Meteor.methods({
'scenarioCreate': function(scenarioObj) {
var newId = Scenarios.insert(scenarioObj);
return newId;
}
});
To catch any error, use try/catch
Note: If you still want to use callback, checkout fibers/future.
Your first error is that you are returning id inside the callback for insert. That doesn't do anything. Then your second is not knowing that methods are synchronously executed. That would mean that you could only use the information available inside the callback using Meteor.wrapAsync. But that's besides the point. The insert function returns the new _id. Meaning you can do this:
Meteor.methods({
'scenarioCreate': function(scenarioObj) {
return Scenarios.insert( scenarioObj );
}
});

Get Meteor Method Return Value Inside Helper Function

I have the following in server/functions.js file:
Meteor.methods({
checkIfVoted: function (postId) {
if (postId) {
...
if (condition is met) {
return true;
} else {
return false;
}
}
}
});
And then the following in client/showPost.js:
Template.showPost.helpers({
alreadyVotedByUser: function () {
var answer = false;
if(this) {
Meteor.call("checkIfVoted", this._id, function(err, response) {
if (response) { console.log(response); }
answer = response;
});
}
console.log(answer);
return answer;
}
});
When I am doing the console.log for response I get the value to be true when the condition is met, but the answer variable does not take it, and still shows as having false as its value.
(I am aware that I put the Meteor methods in the server directory and not in a common directory to be shared between client and server to provide latency compensation)
Please if some one could help me with this, it will be highly appreciated.
On the client, Meteor.call is asynchronous - it returns undefined and its return value can only be accesses via a callback. Helpers, on the other hand, execute synchronously. See the answers to this question for how you can call methods from helpers. Here's a quick solution:
$ meteor add simple:reactive-method
Template.showPost.helpers({
alreadyVotedByUser: function () {
return ReactiveMethod.call('checkIfVoted', this._id);
}
});
The problem with this package is that it can encourage bad behavior, but it should be fine for method calls which don't change state.
Also see the section about helpers in this post.

How to explicitly unsubscribe from a collection?

I have a MongoDB with a large "messages" collection; all messages belonging to a specific groupId. So have started with a publication like this:
Meteor.publish("messages", function(groupId) {
return Messages.find({
groupId: groupId
});
});
and a subscription like this:
Deps.autorun(function() {
return Meteor.subscribe("messages", Session.get("currentGroupId"));
});
This got me into trouble because initially currentGroupId is undefined but sill mongod would use up the CPU to find messages with groupId == null (although I know there are none).
Now, I tried to rewrite the publication as follows:
Meteor.publish("messages", function(groupId) {
if (groupId) {
return Messages.find({
groupId: groupId
});
} else {
return {}; // is this the way to return an empty publication!?
}
});
and/or to rewrite the subscription to:
Deps.autorun(function() {
if (Session.get("currentGroupId")) {
return Meteor.subscribe("messages", Session.get("currentGroupId"));
} else {
// can I put a Meteor.unsubscribe("messages") here!?
}
});
which both helps initially. But as soon as currentGroupId becomes undefined again (because the user navigates to a different page), mongod is still busy requerying the database for the last subscribed groupId. So how can I unsubscribe from a publication such that the mongod is stopped being queried?
According to the documentation it must be http://docs.meteor.com/#publish_stop
this.stop()
Call inside the publish function. Stops this client's subscription;
the onError callback is not invoked on the client.
So something like
Meteor.publish("messages", function(groupId) {
if (groupId) {
return Messages.find({
groupId: groupId
});
} else {
return this.stop();
}
});
And I guess on the client side you can just remove your if/else like in your first example
Deps.autorun(function() {
return Meteor.subscribe("messages", Session.get("currentGroupId"));
});
I found it more simple and straight-forward to call the .stop() function on the handler which is returned from the .subscribe() call:
let handler = Meteor.subscribe('items');
...
handler.stop();
Simply adding a condition to the publication:
Meteor.publish("messages", function(groupId) {
if (groupId) {
return Messages.find({
groupId: groupId
});
});
and keeping the subscription:
Deps.autorun(function() {
return Meteor.subscribe("messages", Session.get("currentGroupId"));
});
does the job.
There is no need to stop the publication explicitly. Eventually, the MongoDB is not queried anymore after finishing the currently running query and issuing yet another one (which seems to be queued somewhere in the system).
in your case, you should stop the autorun
there is an example in the documentation
Your autorun is actually called with a parameter that allows you to stop it:
Deps.autorun(function (c) {
if (! Session.equals("shouldAlert", true))
return;
c.stop();
alert("Oh no!");
});

dojo/Deferred chaining mechanism not respecting async call

I'm quite new to dojo, but I have a certain error dealing with the Deferred API I can't help
my invoking code is
function openEditor(id, fieldName) {
editOptionsDialog_fetchData(id, fieldName).then(function(data){
console.log("done!");
});
console.log("leaving openEditor!");
}
which calls this function
function editOptionsDialog_fetchData(id, fieldName) {
require(["dojo/ready", "dojo/data/ObjectStore", "dojo/Deferred"], function(ready, ObjectStore, Deferred) {
var store;
var def;
switch (fieldName) {
case "degree":
store = new degreeStore();
def = store.getJsonData();
break;
case "faculty":
store = new facultyStore();
def = store.getJsonData();
break;
default:
console.log("error in editOptionsDialog_fetchData: " + fieldName);
}
return def.then(function(data){
store.data = data.items;
editOptionsDialog_select.setStore(new ObjectStore({ objectStore : store }));
editOptionsDialog_select.store.query({ "id" : id });
editOptionsDialog_select.startup();
});
});
}
where store.getJsonData() creates a Deferred, which I want to use for chaining the Deferred resolving (see additional code after the main text).
The error I receive is
editOptionsDialog_fetchData(id, fieldName).then(function(data)...) is undefined
Since the error message appears right after accessing the openEditor function, it is clear, that the value of the function call has to be undefined, since the callback is not yet done.
My question is, where this misunderstanding of the Deferred API must be within my code, since the purpose is to evaluate the function call of editOptionsDialog AS SOON AS the async call is done and called backed, AND NOT BEFORE this call has finished (in the state where the function call still leads to undefined, but I thought this is the purpose of the then-return).
Thx for your help
--- additional code for getJsonData() ---
getJsonData: function() {
return xhr(this.handlerUrl, {
handleAs: "json",
method: "POST",
data: {
action: "getJsonData"
}
}).then(function(data){
return data;
}, function(err){
alert("Data cannot be fetched in degreeStore.getJsonData! " + err);
});
}
I created a fiddle to demonstrate what you are trying to do.
Basically I am returning the Deferred to the editOptionsDialog_fetchData method from getJsonData. editOptionsDialog_fetchData creates another Deferred that it returns to openEditor. In editOptionsDialog_fetchData, I connect the resolving of the first Deferred to the resolve the second Deferred.
http://jsfiddle.net/cswing/yUTT8/
Resolved the problem by restructuring the code. In principle, the Deferred-object seems not to be able to be returned to a distinct require-clause. Therefore, this worked for me:
var editMultilanguageDialog_Startup;
// one require-clause, wrapping all the Deferred-sensitive statements
require(["dojo/request/xhr", "dojo/json", "dojo/Deferred", "dojo/store/Memory", "dojox/timing", "dojo/domReady!"], function(xhr, json, Deferred, Memory, timing, domReady) {
function editMultilanguageDialog_Startup(id, fieldName) {
// code from former mainForm -> moved into this require-clause
//[...]
// here, the invocation is no longer undefined and waits for the resolve
editMultilanguageDialog_fetchData(id, fieldName).then(function(data){
//[...]
editMultilanguageDialog.show();
});
}
function editMultilanguageDialog_fetchData(id, fieldName) {
// unchanged, returns Deferred
}
});
This is a workaround, I don't know if this feature is on purpose by dojo.

Resources