[英]Meteor method call returns undefined on the client but not on the server
我剛剛意識到這種方法存在根本性的錯誤,並且嵌套的回調不能向其父回調返回一些內容。 我在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;
}
})
這就是我使用Promise和Meteor 1.3+
的新async/await
功能解決我的問題的方法
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,以便它返回一個promise。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.