How can I make client wait for the server return?

I’m using Meteor.call in the client, but it returns undefined immediately didn’t wait for my server function return value. what should I do or is there have any alternative options?

there is an example here: http://meteor-ssr-loadable.minhnguyen.me/test. Test sync method call.
You can find the source code at https://github.com/minhna/meteor-react-ssr
Hopefully it’ll solve your problem.

Meteor.call is asynchronous, so you have to give it a callback to get the result.

There’s three ways you can do this (being javascript):

1. Plan old callback

Meteor.call('do.something', function (error, result) {
    // Code in here will run later after the call has completed
    // Do something with the result
});
// Code below the call will run immediately

2. Use Promises:

new Promise((resolve, reject) => Meteor.call('do.something', (error, result) => {
  // This callback just allows you to use  the Meteor call as a promise
  if (err) return reject(error);
  resolve(result);
}).then(result => {
    // Code in here will run later after the call has completed
    // Do something with the result
}).catch(error => {
  // This will run if there was an error in the Meteor call or in your `then`
});
// Code below the promise will run immediately

3. Use Async/Await

Note that await is only available inside an async function, which will —in turn — return a promise

const result = await new Promise((resolve, reject) => Meteor.call('do.something', (error, result) => {
  // This callback just allows you to use  the Meteor call as a promise
  if (err) return reject(error);
  resolve(result);
});
// This will wait till the call is complete and the promise resolves
// Now do something with result

Now this can be a bit verbose since Meteor.call doesn’t return a promise.
If you use a package like deanius:promise, it simplifies greatly:

const result = await Meteor.callPromise('do.something');
// Do something with result

Or without an async function

Meteor.callPromise('do.something').then(result => {
  // Do something with result
});

You can see that the three ways all build on each other as evolutions of the previous syntax

3 Likes

thx.I use async and await in server side ,then everything works fine . Thx a lot.

1 Like