我有一个尝试操作数据库的 Meteor 方法,如果成功,则调用一个异步方法。我希望能够调用此方法并返回异步调用的结果或数据库操作的错误。
这是(大致)我在服务器上的代码:
Meteor.methods({
'data.update'(id, data) {
Collection.update({id_: id}, {$set: {data: data}}, error => {
if (error) {
// Have method return Meteor error for DB-failure
} else {
callAsync(id, (error, res) => {
if (error) {
// Have method return Meteor error for async call failure
} else {
// Have method return success(res)
}
})
}
})
}
});
我读过 Futures 和 Promises,但我对这些概念还很陌生,我不确定什么时候使用什么。最好我正在寻找一种不依赖 Meteor/ES6 之外的任何第三方库的解决方案。奖金(相关)问题:在让我将回调附加到方法的数据库操作之后通常返回什么?
最佳答案
根据 docs
On the server, if you don’t provide a callback, then update blocks until the database acknowledges the write, or throws an exception if something went wrong. If you do provide a callback, update returns immediately. Once the update completes, the callback is called with a single error argument in the case of failure, or a second argument indicating the number of affected documents if the update was successful.
因此,如果更新
成功,则返回受影响的文档数。在 insert
的情况下,返回插入文档的 _id
。
如前所述,您可以简单地将第三个参数传递给更新函数。
对于 promise 的实现,你可以使用 Meteor.wrapAsync
方法。如果您也需要传递实例变量的状态,您可能还想查看 Meteor.bindEnvironment
来实现这一点。
关于javascript - meteor ,链接方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39469674/