Calling the Meteor method returns undefined on the client, but not on the server

UPDATE

I just realized something fundamentally wrong with this approach, and that nested callbacks cannot return something to their parent callback. I came to the end of the JS world and came from an era Promisesand did not know that this is a problem with callbacks. But I have not seen enough examples for Meteor using promises, so I used callbacks instead. However, if this code can be improved, I would really appreciate it.

Question

So, I call the method from the client using:

Meteor.call('cart.useProfileAddress', {}, (error, address) => {
  console.info('Address', address) // this returns undefined on client
})

This is the method in my api/carts/cartsMethod.js

export const useProfileAddress = new ValidatedMethod({
  name: 'cart.useProfileAddress',
  validate(args) {
    //
  },
  run(args) {
    const person = Persons.findOne({'userId': Meteor.userId()});
    // If I do the return here I get the address in the browser as defined.
    // return person.address

    // I'm calling another method under here:
    getClosestStore.call({address: person.address}, (error, result) => {
      // And another one method call here:
      updateCartAddress.call({address: person.address}, (error, result) => {
        // So once all the callbacks are done return the address here.
        // However the problem is I get `undefined` on the client.
        if (!error) {
          // console displays something on the Server but is `undefined` on the Client
          console.info('Returning Address', person.address)
          return person.address
        }
      })
    })
  }
})

What could be the problem with the code above? Maybe because I'm trying to get the value from a nested callback?

- , ? , Node, promises, Meteor ( 1.4). .

+4
2

Promise async/await Meteor 1.3+

export const useProfileAddress = new ValidatedMethod({
  name: 'cart.useProfileAddress',
  validate(args) {
    //
  },
  run(args) {
    return ((async () => {
      const person = Persons.findOne({'userId': Meteor.userId()});
      const storeId = await getClosestStore.callPromise({address: person.address})
      const newAddress = await updateCartAddress.callPromise({address: person.address})

      return newAddress
    })())
  }
})

didericis: callpromise-mixin, .

+3

, . , . :

export const useProfileAddress = new ValidatedMethod({
  // ...
  run(args) {
    const person = Persons.findOne({'userId': Meteor.userId()});

    const result1 = getClosestStore.call({address: person.address});

    // use result1 if you need to

    const result2 = updateCartAddress.call({address: person.address});

    // // use result2 if you need to

    return person.address;
  }
})
+3

Source: https://habr.com/ru/post/1669108/


All Articles