我还能使用 Meteor.call 吗?
可以,但我们建议您仅将其用于调用没有方法存根的方法,或者当方法存根是同步时。
事实上,如果您使用 Meteor.call
调用具有异步方法存根的方法,我们会记录一条警告消息,因为它可能导致意外行为。
Meteor.callAsync
是调用方法的标准,并支持任何方法,包括那些具有异步方法存根的方法。
这里还需要记住存根是什么。存根是在调用方法时立即运行的服务器端方法的客户端模拟,允许客户端在收到服务器的响应之前乐观地更新其状态。因此,基本上在客户端定义的任何 Meteor 方法都被视为存根。
如何从 Meteor.call 迁移到 Meteor.callAsync
从 Meteor.call
迁移到 Meteor.callAsync
的示例
js
import { Meteor } from "meteor/meteor";
let data, error;
Meteor.call("getAllData", (err, res) => {
if (err) {
error = err;
} else {
data = res;
}
});
// render data or error
js
import { Meteor } from "meteor/meteor";
import { Mongo } from "meteor/mongo";
const MyCollection = new Mongo.Collection("myCollection");
Meteor.methods({
getAllData() {
return MyCollection.find().fetch();
},
});
js
import { Meteor } from "meteor/meteor";
try {
const data = await Meteor.callAsync("getAllData");
// render data
} catch (error) {
// render error
}
js
import { Meteor } from "meteor/meteor";
import { Mongo } from "meteor/mongo";
const MyCollection = new Mongo.Collection("myCollection");
Meteor.methods({
async getAllData() {
return await MyCollection.find().fetchAsync();
},
});
Meteor.callAsync 的有效使用注意事项
这些限制已在由 Zodern 创建的此 包 中得到解决,后来,我们将解决方案移至 核心。
但是,异步存根问题没有完美的解决方案。
为了确保其他代码在异步存根运行时不会运行,异步存根不能使用这些 API
- fetch/XMLHttpRequest
- setTimeout 或 setImmediate
- indexedDB
- Web Workers
- 任何其他等待宏任务的异步 Web API
使用这些 API 可能会允许其他代码在异步存根完成之前运行。
如果使用了其中一个 API,控制台将显示警告
Method stub (<method name>) took too long and could cause unexpected problems. Learn more at https://v3-migration-docs.meteor.js.cn/breaking-changes/call-x-callAsync.html#what-are-the-limitations-of-call-meteor-callasync