【发布时间】:2017-06-25 14:36:47
【问题描述】:
更新
我刚刚意识到这种方法存在根本性的错误,嵌套回调无法将某些内容返回到其父回调。我在 JS 世界中来得很晚,来自Promises 时代,不知道这是回调的问题。但是我没有看到足够的 Meteor 使用 Promise 的例子,所以我使用了回调。但是,如果可以改进此代码,我将不胜感激。
问题
所以我从客户端调用一个方法,使用:
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
}
})
})
}
})
上面的代码可能有什么问题?可能是因为我试图从嵌套回调中获取值?
还有谁知道如何避免这些嵌套回调?我知道如何使用 Promise 在 Node 上做到这一点,但在 Meteor 中(我正在使用 1.4)我仍然一无所知。
【问题讨论】:
标签: javascript meteor meteor-accounts