如何将DDPClient与promises一起使用?

时间:2014-06-19 01:56:38

标签: javascript node.js meteor promise when-js

我正在尝试将when.jsddpclient一起使用。我写的代码位于帖子的底部。当我尝试使用它时,我在下面得到以下错误。有关如何解决此错误的任何想法?我知道另一个使用promises的DDPclient,但我并不热衷于添加额外的promise库。

Potentially unhandled rejection TypeError: Object #<Object> has no method '_nextId'
    at DDPClient.call (/Source/proj/node_modules/ddp/lib/ddp-client.js:329:17)
    at /Source/tellme/updater/node_modules/when/node.js:89:7
    at tryCatchReject (/Source/proj/node_modules/when/lib/makePromise.js:790:14)
    at FulfilledHandler.when (/Source/tellme/updater/node_modules/when/lib/makePromise.js:621:9)
    at ContinuationTask.run (/Source/tellme/updater/node_modules/when/lib/makePromise.js:741:24)
    at Scheduler._drain (/Source/proj/node_modules/when/lib/scheduler.js:56:14)
    at Scheduler.drain (/Source/proj/node_modules/when/lib/scheduler.js:21:9)
    at process._tickCallback (node.js:419:13)
    at Function.Module.runMain (module.js:499:11)
    at startup (node.js:119:16)

以下代码:

"use strict";
var when           = require('when'),
    node           = require('when/node'),
    DDPClient      = require('ddp');


var ddpclient = new DDPClient({
    host: "localhost",
    port: 3000
});

var ddpconnect = node.lift(ddpclient.connect);
var ddpcall = node.lift(ddpclient.call);

//var ddpConnectPromise = node.lift(ddpclient.connect);

var obj = {"name": "john","age":25};

when(ddpconnect).then
(ddpcall("processObj", obj)).
    catch(function (error) {
        console.log(error);
    }).
    done();

编辑:以下内容似乎让我更接近,但我遇到了 [TypeError:Object processObj没有方法'addListener'] 错误。

"use strict";
var when           = require('when'),
    node           = require('when/node'),
    DDPClient      = require('ddp');

var ddpConnectPromise = node.liftAll(DDPClient);

var ddpclient = new ddpConnectPromise({
    host: "localhost",
    port: 3000
});

var obj = {"name": "john","age":25};
when(ddpclient.connect).then(function (ddpclient) {
    ddpclient.call("processObj", sampleJSON);
}).
    catch(function (error) {
        console.log(error);
    }).
    done();

1 个答案:

答案 0 :(得分:0)

如果您不介意使用bluebird,那么您可以使用promisifyAll:

var Promise = require("bluebird");
Promise.promisifyAll(require("ddp").prototype);
var DDPClient = require("ddp");    

var ddpclient = new DDPClient({
  host: "localhost",
  port: 3000,
  /* optional: */
  auto_reconnect: true,
  auto_reconnect_timer: 500,
  use_ejson: true,           // Use Meteor's EJSON to preserve certain data types.
  use_ssl: false,
  maintain_collections: true // Set to false to maintain your own collections.
});


var obj = {"name": "john","age":25};

ddpclient.connectAsync().then(function(ddpclient) {
    return ddpclient.callAsync("process", {}); // params is a required argument
}).then(function(callResult) {

}); // Logging errors is useless when using bluebird, so leave the .catch out