gpt4 book ai didi

javascript - Meteor 方法回调结果未定义

转载 作者:行者123 更新时间:2023-12-03 02:43:58 24 4
gpt4 key购买 nike

我已经有一段时间没有在 Meteor 中编码了,但是我有这个 Meteor 方法,它创建一个任务并返回 ID,以及另一个将该任务附加到项目的方法:

Meteor.methods({
createTask(task) {
// TODO Add a check here to validate
Tasks.insert(task, (err, id) => {
if (err) {
throw new Meteor.Error(err);
}
id = {id: id};
console.log('Returning id: ', id);
return id;
});
}
});

Meteor.methods({
appendTaskToProject(projectId, taskId) {
// TODO Add check here to validate
const project = Projects.findOne({_id: projectId});
if (project) {
if (!project.tasks) {
project.tasks = [];
}
project.tasks.push(taskId);
Projects.update({_id: projectId}, project, (err, id) => {
if (err) {
throw new Meteor.Error(err);
}
});
} else {
throw new Error("Could not find project");
}
}
});

我试图在客户端上调用它,如下所示:

Meteor.call('createTask', task, (err, taskId) => {
console.log('err: ', err);
console.log('taskId: ', taskId);
if (err) {
this.setState({ error: err.message});
} else {
Meteor.call('appendTaskToProject', projectId, taskId, (err, result) => {
if (err) {
this.setState({ error: err.message});
} else {
this.setState({ newTaskDialogOpen: false })
}
});
}
});

我遇到的问题是回调中未设置taskId。从方法端我看到服务器中的日志消息如下:

I20180110-07:30:46.211(-5)? Returning id:  { id: 'a3nS9GcRhuhhLiseb' }

在客户端:

Returning id:  {id: "a3nS9GcRhuhhLiseb"}id:
Tasks.jsx:43 err: undefined
Tasks.jsx:44 taskId: undefined

所以我知道它正在返回一些东西,但回调只是没有得到它。我知道我可能应该更改 createTask 以仅获取任务和 projectId 来链接它,但我想尝试找出为什么它没有将 Meteor 方法的结果获取到客户端的回调中。

最佳答案

Meteor API 文档 collection methods就像 insert 所说:

On the server, if you don’t provide a callback, then insert blocks until the database acknowledges the write, or throws an exception if something went wrong. If you do provide a callback, insert still returns the ID immediately. Once the insert completes (or fails), the callback is called with error and result arguments. In an error case, result is undefined. If the insert is successful, error is undefined and result is the new document ID.

将此信息应用到您的代码中将创建以下内容:

Meteor.methods({
createTask(task) {
// TODO Add a check here to validate
return Tasks.insert(task, (err, id) => {
if (err) {
throw new Meteor.Error(err);
}
});
}
});

这将立即返回新生成的 ID,但有一个缺点,即随后会抛出错误。因此,您最好采用直接方式并执行“类似同步”:

Meteor.methods({
createTask(task) {
// TODO Add a check here to validate
return Tasks.insert(task);
}
});

meteor 方法会自动包装代码,以便在返回正值时,您的客户端将收到一个 null 错误值和 _id 值作为结果。如果插入过程中发生错误,该方法会自动在客户端回调中将错误作为错误返回,并且结果将为 null。

如果您担心代码的同步性质,请阅读 this part of the guide关于方法。

同样适用于您的更新方法:

Meteor.methods({
appendTaskToProject(projectId, taskId) {
// TODO Add check here to validate
return Projects.update({_id: projectId}, {$push: {tasks: taskId});
}
});

请注意,我将此方法总结为更面向 mongo 的方法。

关于javascript - Meteor 方法回调结果未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187881/

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