I’ve been trying to avoid callback hell in Meteor but first, I’ll explain my problem:
I have some Meteor methods declared in server, and I invoke them using Meteor.call in client, but the main problem is I have tons of callbacks making debugging a really difficult task to make (and manteinance too…). This wouldn’t be an issue if I work with a “small” project, but I’m building a big one and I was planning on using promises but for my surprise… it’s not working since Meteor.call only accepts callbacks.
I’ve read a lot of posts here and in stackoverflow and none of them can help me… is there any solution to this? (I tried deanius:promise package and it’s still the same…)
Edit: Here’s the code I’m trying to test with; Method declarations in server, method calls in client. https://themeteorchef.com/snippets/what-are-javascript-promises/
Yes, I’ve checked that post, but the keyword “await” pops me an error in client console, like it doesn’t recognize the keyword. Should I need to add some package?
What version of Meteor are you using? The ecmascript
package provides ES6/async/await. However, that package is generally added by default.
1 Like
I’m using 1.4.2. The code I’m trying to run using await its the following:
Template.hello.onCreated(async function...) ... Template.hello.onRendered(() => { const response1 = await Meteor.call('myFunction'); const response2 = await Meteor.call('myFunction2'); ...}
I get "unexpected token after first await word…I think it’s not because is inside an onRendered block right?
Ah, well, you need to make the onRendered
an async function (btw you should not be using the ES6 fat arrow in onCreated
and onRendered
as it overwrites the default context).
Also, check through that thread. You can’t just await
on a Meteor.call
- you have to have a promisified call, such as the example I showed earlier in that thread (callWithPromise
).
Template.hello.onRendered(async function() {
const response1 = await callWithPromise('myFunction');
const response2 = await callWithPromise('myFunction2');
...
});
1 Like
Making those changes it worked! Thanks a lot, and sorry for not being aware of all the details of that post!
2 Likes
Don’t be sorry - some of those posts are long and hard to follow. Glad you got there in the end
1 Like
@robfallows your snippet callWithPromise
must be in the official docs of Meteor! Care to create a PR for it ? Or a package why not. Meteor.callSync() I will definitely add it in the Meteor-Tuts
1 Like