Nisha Bhooshan
Nisha Bhooshan

Reputation: 11

Meteor.call with await/promise doesn't seem to synchronous

I've been trying to call meteor.call in synchronous way. I tried to follow the example given in the meteor forum doesn't seem to work.

const callWithPromise = (method, myParameters) => {
     return new Promise((resolve, reject) => {
     Meteor.call(method, myParameters, (err, res) => {
     if (err) reject('Something went wrong');
        resolve(res);
     });
  });
 }

The following function diiidn't wait for the above and doStuff() returned immediateley after call.

async function doStuff() {
    const myValue1 = await callWithPromise('myMethod1', someParameters);
    const myValue2 = await callWithPromise('myMethod2', myValue1);
}

Any Input in the above is appreciated.

Upvotes: 1

Views: 603

Answers (2)

Mikkel
Mikkel

Reputation: 7777

Yes, await doesn't exactly do what you might expect (or want). And then it needs to be contained in an async function to be used :( It is still dealing with promises, and you need to be aware of that.

Meteor does, however, provide a Promise implementation that allows one to wait without needing to be inside an async function.

import { Promise } from 'meteor/promise'

and in your code you can do this:

const result = Promise.await(Metor.call('server-method',params))

result then contains whatever was returned by the Meteor method, so it behaves like a regular function call.

Upvotes: 3

Christian Fritz
Christian Fritz

Reputation: 21364

As Bergi already pointed out, even an async function will return right away -- as the name suggests! -- even if inside of it you are allowed to await things. So you'll need to await on the async function, too. Here is a simplified example:

const wait = () => { return new Promise((resolve, reject) => setTimeout(resolve, 2000)); }
async function doit() { await wait(); console.log('waited'); }
doit(); console.log('the end');

will result in:

the end
waited

however:

await doit(); console.log('the end');

will do what you seem to want, namely:

waited
the end

Upvotes: 1

Related Questions