更新
我刚意识到这种方法存在根本性问题,嵌套回调函数无法将结果返回给其父回调函数。我是在JavaScript世界中很晚才了解了这一点,来自于Promises
时代,不知道这是回调函数的问题。但是,我没有看到足够的Meteor使用Promises的示例,所以我使用了回调函数。然而,如果这段代码可以改进,我会非常感激。
问题
所以我正在通过以下方式从客户端调用一个方法:
Meteor.call('cart.useProfileAddress', {}, (error, address) => {
console.info('Address', address) // this returns undefined on client
})
这是我在
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
}
})
})
}
})
以上代码的问题可能是什么?是否因为我试图从嵌套回调中获取值?
还有,有人知道如何避免这些嵌套回调吗?我知道如何在Node
中使用promises来解决,但在Meteor(我正在使用1.4
)中仍然一筹莫展。
getClosestStore.call
总是异步的,因为它是另一个从另一个API获取距离的异步调用的包装器。是否可以在方法内部传递回调函数,以便我可以在最内层的回调中调用它?如果一切都失败了,我将使用promises。 - JohnnyQgetClosestStore
方法中使用 Promise。 - kkkkkkk