承诺和 Meteor.call()
Promises and Meteor.call()
我有一个 Meteor.method()
服务器端 returns 来自 oracledb
的承诺。客户端我有:
Meteor.call('myMethod', (error, result) => {
result.then() // err -> no .then() method?,
});
那么result
是什么?它没有 .then()
方法,所以它不是一个承诺?
Meteor 没有"send"对客户的承诺。
服务器 returns 一旦在服务器上解决(或拒绝)了承诺,而不是在从方法本身返回承诺的那一刻,给客户端的结果值(触发回调) (除非退货时已经结算)
您也可以使用async/await来简化代码。
此处a blog post包含有关在方法中使用异步代码的更多详细信息。
注:
从服务器发送的值使用 EJSON 序列化。对象方法、getter 等都从中剥离,除非您创建 custom serializer。在某些情况下,序列化甚至可能会失败(我认为它发生在某些 moment
对象上)并导致返回 undefined
。
Meteor 默认不使用 promises,但是,您可以将 Meteor.calls 包装到一个 promise 函数中,如下所示
const callWithPromise = (method, myParameters) => {
return new Promise((resolve, reject) => {
Meteor.call(method, myParameters, (err, res) => {
if (err) reject('Something went wrong');
resolve(res);
});
});
}
(async function() {
const myValue1 = await callWithPromise('myMethod1', someParameters);
const myValue2 = await callWithPromise('myMethod2', myValue1);
})();
示例代码已复制自 Meteor forum。
此外,this topic 让您更好地了解如何在 Meteor 调用中利用 Aysnc/Await 语法或 Promises。
我有一个 Meteor.method()
服务器端 returns 来自 oracledb
的承诺。客户端我有:
Meteor.call('myMethod', (error, result) => {
result.then() // err -> no .then() method?,
});
那么result
是什么?它没有 .then()
方法,所以它不是一个承诺?
Meteor 没有"send"对客户的承诺。
服务器 returns 一旦在服务器上解决(或拒绝)了承诺,而不是在从方法本身返回承诺的那一刻,给客户端的结果值(触发回调) (除非退货时已经结算)
您也可以使用async/await来简化代码。
此处a blog post包含有关在方法中使用异步代码的更多详细信息。
注:
从服务器发送的值使用 EJSON 序列化。对象方法、getter 等都从中剥离,除非您创建 custom serializer。在某些情况下,序列化甚至可能会失败(我认为它发生在某些 moment
对象上)并导致返回 undefined
。
Meteor 默认不使用 promises,但是,您可以将 Meteor.calls 包装到一个 promise 函数中,如下所示
const callWithPromise = (method, myParameters) => {
return new Promise((resolve, reject) => {
Meteor.call(method, myParameters, (err, res) => {
if (err) reject('Something went wrong');
resolve(res);
});
});
}
(async function() {
const myValue1 = await callWithPromise('myMethod1', someParameters);
const myValue2 = await callWithPromise('myMethod2', myValue1);
})();
示例代码已复制自 Meteor forum。
此外,this topic 让您更好地了解如何在 Meteor 调用中利用 Aysnc/Await 语法或 Promises。