How to return the value from meteor.call. Please refer the code for more detail.
highlightStroke: "rgb(15,138,12)",
data:Meteor.call('dataCallYou', Session.get('areaHome'), function(error,you){
if(_.isEmpty(you)){
you=[0,0,0,0]
}
})
Meteor.call is an asynchronous task.
See How do I return the response from an asynchronous call?
Related
I've made a function that calls on the FireBase database and will return a MutableList. However, when I try to make it return on a specific line, it says it requires a Unit instead of the MutableList.
fun firebaseCollect(key: String): MutableList<CustomList> {
var ref = FirebaseDatabase.getInstance().getReference(key)
var lessonList = mutableListOf<CustomList>()
ref.addValueEventListener(object: ValueEventListener{
override fun onCancelled(p0: DatabaseError?) {
}
override fun onDataChange(p0: DataSnapshot?) {
if (p0!!.exists()) {
lessonList.clear()
for (index in p0.children) {
val lesson = index.getValue(CustomList::class.java)
lessonList.add(lesson!!)
}
return lessonList
}
}
})
return lessonList
}
Type mismatch. Required: Unit, Found: MutableList< CustomList > is found at the first return lessonList since what I am asking for it to return is a MutableList not a Unit. I am confused as to why this happens. The last return would give an empty list. It is currently my first jab at FireBase and this is a practice I am doing. The rules for read and write have been set to public as well. How should I recode the function that I am able to return the data from FireBase into the function and passed back to the caller?
Firebase APIs are asynchronous. For your case, that means addValueEventListener returns immediately. Then, some time later, the listener you passed to it will be invoked with the data you're looking for. Your return statement in the callback doesn't actually return any data to the caller. In fact, you can't return anything from that callback. At the bottom of your function, when you return lessonList, you're actually returning an initially empty list to the caller, which may change later when the data finally arrives.
To get a better sense of how your code works, put log lines in various places, and see for yourself the order in which the code is invoked. You can read more about why Firebase APIs are asynchronous by reading this article. The bottom line is that you'll need to interact with the asynchronous APIs using asynchronous programming techniques. Don't try to make them synchronous.
Data is loaded asynchronously from Firebase. Once the data is fetched the method onDatachange() is invoked.
You are returning lessonList inside onDatachange(). Return type of onDatachange() is void(Unit in kotlin). This is the reason for the type mismatch error.
For returning the result from the method onDatachange() try this.
what happens when promise function inside asynchronous function never resolves or rejected ,so inside below save method if both initial if conditions get not satisfied what will happen, it's not giving error,will it wait there forever till response receive?
save().then(results=>{
})
save():promise<any>{
if (conditionA) {
return http request
}
if (conditonB) {
return http request}
}
}
If your promise sometimes returns a promise, then it should always return a promise. The usual design pattern if you find you don't need to have a promise to return in some code paths is that you just do a return Promise.resolve(). So, keep with your pseudo-code, you'd do something like this:
save().then(results=>{
})
save():promise<any>{
if (conditionA) {
return request(...);
} else if (conditonB) {
return request(...);
} else {
return Promise.resolve(...);
}
}
You fill in the ... parts above to make sense for your function. But, if you sometimes return a promise, then ALWAYS return a promise. Then, the caller can just consistently use the returned promise. If the work is already done (or there was nothing to do), then you just return an already resolved promise and the caller always gets a consistent return value which they can use as a promise.
Note, that none of this matches the title of your question, but it does fully match the body of your question. Is your title just wrong or is there some part of your question description that is missing?
A simple answer should be ,save() cannot be undefined if any kind of promise is returned from the method including the service call(http call),
if it never resolves it will never go into then part of the handler ,but it cannot give the error undefined.
undefined error can be given when no condition satisfied in the if else conditions and nothing returns.
When I try to call methods inside helpers, reactivity doesn't work. here is my code :
server side method code
Meteor.methods({
getLastContact:function(){
return contacts.findOne({},{sort: {contactID: -1},fields: {contactID:1}})
}
})
client side calling method
Template.createVendor.helpers({
lastIDD: function () {
Meteor.call('getLastContact',function(err,res){
console.log(res.contactID);
}); }});
if some new data is added, template helper losses reactivity and client does not get update.
Can anyone point out what am I doing wrong?
There is a package that makes meteor methods reactive. check out meteor-reactive-method.
It will do exactly what you are trying to do.
When you are calling a method in client helpers you should use
return ReactiveMethod.call("method_name",Parameter1,Parameter2,..);
Include the package for ReactiveMethod call.
I understand that Meteor methods let you do a client to server call, but what's the best approach to call another function or method from a Meteor method, i.e. a server to server call.
Right now if I do a regular JS function call it only works if the JS file is in the lib folder. But I need it to be in the server folder.
Here is the code
I have a topics collection which sits in the collection folder and has the following
I have the following which is a collection
Meteor.methods({
topicPost: function(topicAttributes) {
var user = Meteor.user(),
topicWithSameTitle = Topics.findOne({title: topicAttributes.title});
// ensure the user is logged in
if (!user)
throw new Meteor.Error(401, "You need to login to add a new topic");
Meteor.call('checkUser');
}
});
I then have the following method which sits in the server folder
Meteor.methods({
checkUser: function () {
alert('aaaa');
}
});
This works, but it's not a great solution. My method for handling this is to have all of my functions outside the Meteor.methods, and simply relay to the proper functions when necessary.
// Client
Meteor.call('foo');
And:
// Server
Meteor.methods({
foo: function() {
foo();
}
});
foo = function() {
foo = bar;
};
The advantage is that the foo fn can be called from anywhere on the server without a Meteor.call. Meanwhile, Meteor.methods only exposes what is absolutely necessary to the client.
[EDIT] There is some ambiguity as to which 'foo' you're talking about; obviously the server knows you mean the one outside the methods call. But if you're feeling confused, you can always rename one or the other. The advantage to this is that there is minimal refactoring involved.
Just to clarify for readers who don't notice that the OP's code actually contains the answer, you just do
Meteor.call('checkUser');
on the server. Per the meteor docs (https://docs.meteor.com/api/methods.html#Meteor-call), on the server, if you use Meteor.call() without a callback argument, the call runs synchronously and waits for the result. For example, if 'checkUser' was written to provide a userId value, you'd just do
let userId = Meteor.call('checkUser');
On the client, though, you have to provide a callback function as an argument to Meteor.call(), and the userId would be provided asynchronously to your callback function.
When trying to render my template, i want to load the data from the server. I'm trying to use Meteor.call but as per the documentation, i'm clearly not in a stub.
If I use Meteor.call inside of an event handler, the response i get back is correct. If i call it within the template.created or similar, i get an undefined response. I guess i could use async call to do it and then render it when available. But is there another way?
I don't want the clients to have direct access to the DB, i want it to come from the server.
//This doesn't work
Template.config.created = function() {
console.log(Meteor.call('getValue')); //returns undefined
};
//This works
Template.config.events({
'blur #button' : function () {
console.log(Meteor.call('getValue')); //Prints value
}
Any clues?
D
You need to use a callback in your Meteor.call
Template.config.created = function() {
Meteor.call('getValue', function(error, data) {
if(error){
//do stuff to handle error
}
console.log(data);
});
};
From the docs:
On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn't have fibers, so there is not actually any way it can block on the remote execution of a method.
I'm not sure why your event handler call is working... There isn't any way to synchronously get a server response like that in JavaScript without Fibers. The solution is simply to provide an asynchronous callback. This isn't really a Meteor limitation, it's just a JavaScript limitation.