流星,链接方法调用

Meteor, chaining method calls

本文关键字:调用 方法 链接 流星      更新时间:2023-09-26

我有一个尝试操作数据库的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)
                    }
                })
            }
        })
    }
});

我读过关于未来和承诺的书,但我对这些概念不熟悉,我不确定什么时候用什么。最好我正在寻找一个解决方案,不依赖于任何第三方库以外的流星/ES6。附加(相关)问题:在数据库操作之后,通常会返回什么,让我们将回调附加到一个方法?

根据docs

在服务器上,如果你不提供回调,那么更新块直到数据库确认写入,否则抛出异常出了什么问题。如果你提供了回调,update返回立即。更新完成后,回调函数将被调用失败时使用单个错误参数,或者使用第二个参数如果更新是,则指示受影响文档的数量成功。

因此,如果update成功,则返回受影响的文档数量。如果是insert,则返回插入文档的_id

您可以简单地将第三个参数传递给如上所述的更新函数。

对于承诺实现,可以使用Meteor.wrapAsync方法。如果您也需要传递实例变量的状态,您可能还需要查看Meteor.bindEnvironment来实现这一点。

您可以考虑使用Promises,但是在Meteor生态系统中还有另一种相当标准的方法来处理类似的事情。您可以使用Meteor.wrapAsync将基于异步回调的函数转换为基于光纤的版本。这样就可以利用返回值和异常。下面是一个简单的例子:

假设我们在某个地方有一个名为increaseLifetimeWidgetCount的内部函数,它增加了数据库中某个地方的生命周期小部件计数,然后调用一个回调函数,错误或新更新的生命周期计数:
function increaseLifetimeWidgetCount(callback) {
  // ...
  // increase the lifetime widget count in the DB somewhere, and 
  // get back the updated widget count, or an error.
  // ...
  const fakeError = null;
  const fakeLifetimeWidgetCount = 1000;
  return callback(fakeError, fakeLifetimeWidgetCount);
}

2)假设我们定义了一个简单的方法,它将在数据库中创建一个新的Widget,调用内部increaseLifetimeWidgetCount函数,然后返回新更新的生命周期Widget计数。由于我们希望返回更新的生命周期小部件计数,因此我们将基于increaseLifetimeWidgetCount的回调函数包装在Meteor.wrapAsync调用中,并返回结果:

Meteor.methods({
  newWidget(data) {
    check(data, Object);
    Widgets.insert(data);
    const increaseLifetimeWidgetCountFiber =
      Meteor.wrapAsync(increaseLifetimeWidgetCount);
    const lifetimeWidgetCount = increaseLifetimeWidgetCountFiber();
    return lifetimeWidgetCount;
  }
});

3)然后我们可以从客户端调用newWidget方法,使用异步回调,并处理返回的错误或返回的生命周期小部件计数:

Meteor.call('newWidget', { 
  name: 'Test Widget 1' 
}, (error, result) => { 
  // Do something with the error or lifetime widget count result ...
  console.log(error, result);
});