gpt4 book ai didi

javascript - Meteor 方法调用在客户端返回 undefined 但在服务器端不返回

转载 作者:搜寻专家 更新时间:2023-11-01 05:20:40 25 4
gpt4 key购买 nike

更新

我刚刚意识到这种方法存在根本性的错误,嵌套回调无法将某些内容返回到其父回调。我进入 JS 世界的时间较晚,来自 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
}
})
})
}
})

上面的代码可能有什么问题?会不会是因为我试图从嵌套回调中获取值?

还有谁知道如何避免这些嵌套回调?我知道如何使用 promises 在 Node 上执行此操作,但在 Meteor 中(我使用的是 1.4)我仍然一无所知。

最佳答案

方法可以在服务器上同步运行,因此您不需要使用回调。方法执行后会返回结果,如果出错会抛出异常。试试这个:

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;
}
})

关于javascript - Meteor 方法调用在客户端返回 undefined 但在服务器端不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42105294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com