在Promisecallback中调用meteor方法

我正在尝试使用这个NPM包:我的Meteor应用程序中的Gumroad-API 。 当我尝试在Promisecallback中执行Meteor方法调用(或集合插入)时,遇到服务器端的问题。

以下是我的两个Meteor方法的代码:

Meteor.methods({ testMethod: () => { console.log('TEST METHOD RUN'); }, fetchGumroadData: () => { const Gumroad = Meteor.npmRequire('gumroad-api'); let gumroad = new Gumroad({ token: Meteor.settings.gumroadAccessKey }); Meteor.call('testMethod'); // runs fine gumroad.listSales('2014-12-04', '2099-12-04', 1).then((result) => { console.log('1'); // runs fine Meteor.call('testMethod'); // execution halts here w/o error msg console.log('2'); // this never runs }); }, }); 

每当我尝试在其中执行Meteor.call()Meteor.call()callback中的代码总是会暂停(没有错误信息)。

当我用一个Collection.insert()replaceMeteor.call()时,我得到了相同的行为,如: Sales.insert({text:'test'});

老问题,但是,这个失败的原因是因为你的callback中没有Meteor环境。

告诫这是未经testing的代码

 Meteor.methods({ testMethod: () => { console.log('TEST METHOD RUN'); }, fetchGumroadData: () => { const Gumroad = Meteor.npmRequire('gumroad-api'); let gumroad = new Gumroad({ token: Meteor.settings.gumroadAccessKey }); Meteor.call('testMethod'); // runs fine gumroad.listSales('2014-12-04', '2099-12-04', 1) .then(Meteor.bindEnvironment((result) => { console.log('1'); // runs fine Meteor.call('testMethod'); // execution halts here w/o error msg console.log('2'); // this never runs })); }, }); 

有关bindEnvironment和wrapAsync的教程可以在这里find: https ://www.eventedmind.com/items/meteor-what-is-meteor-bindenvironment

我没有太多的承诺,所以我不知道你为什么看到这个错误。 当使用这样的外部API时,我通常使用wrapAsync,所以我可以以同步的方式编写我的代码,但仍然可以达到相同的结果。

在你的情况下,看起来像这样:

 Meteor.methods({ testMethod: () => { console.log('TEST METHOD RUN'); }, fetchGumroadData: () => { const Gumroad = Meteor.npmRequire('gumroad-api'); let gumroad = new Gumroad({ token: Meteor.settings.gumroadAccessKey }); Meteor.call('testMethod'); // runs fine let wrappedListSales = Meteor.wrapAsync(gumroad.listSales, gumroad); let result = wrappedListSales('2014-12-04', '2099-12-04', 1); console.log('1'); Meteor.call('testMethod'); console.log('2'); }, }); 

Meteor.wrapAsync的第二个参数是可选的,可能不需要,这取决于gumroad API的性质

我最终放弃了NPM软件包并编写了我自己的API调用。 我无法弄清楚如何在.then()调用我的电话。 代码如下:

 fetchGumroadData: () => { let options = { data: { access_token: Meteor.settings.gumroadAccessKey, before: '2099-12-04', after: '2014-12-04', page: 1, } }; HTTP.call('GET', 'https://api.gumroad.com/v2/sales', options, (err,res) => { if (err) { // API call failed console.log(err); throw err; } else { // API call successful Meteor.call('testMethod'); } }); }