简体   繁体   中英

Promises and Meteor.call()

I have a Meteor.method() that server side returns a promise from oracledb . Client side I have:

Meteor.call('myMethod', (error, result) => {
  result.then() // err -> no .then() method?, 
});

So what is result ? It does not have a .then() method, so it is not a promise?

Meteor does not "send" the promise to the client.

The server returns a result value to the client (which triggers the callback) once the promise is resolved (or rejected) on the server, and not at the moment the promise is returned from the method itself (unless it is already settled when returned).

You can also use async/await to simplify the code.

Here is a blog post with more details about the using asynchronous code in methods.

Note:

The value sent from the server is serialized using EJSON. Object methods, getters, etc. are stripped from it, unless you create a custom serializer . In some cases, serialization might even fail (I think it happened with certain moment objects) and result in undefined being returned.

Meteor is not using promises by default, however, you can wrap your Meteor.calls into a promise function as below

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

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

Sample code has copied from Meteor forum .

Also, this topic gives you a better insight in taking advantages of Aysnc/Await syntax or Promises in Meteor calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM