Q.defer Bluebird中的解决方法

时间:2014-09-03 11:25:33

标签: coffeescript bluebird

我正在将coffeeScript代码从Q迁移到Bluebird,看起来我一直在使用promise,因为Bluebird的文档显然不鼓励使用Promise.defer

带有Q的客户端服务器的简化版本如下:

Q = require 'q'

handleRequest = (msg) ->
  console.log "Server received #{msg} \n"

  deferred = Q.defer()

  setTimeout () ->
    deferred.resolve "bar"
  , 2000

  deferred.promise

handleRequest "foo"
.then (msg) ->
  console.log msg

基本上我有一个带有promise的函数,它将在2秒后异步解析。

在Bluebird中尝试相同的方法时,我得到一个TypeError,说对象函数Promise(解析器)没有'then'方法(整个错误代码在这篇文章的末尾)

Promise = require 'bluebird'

handleRequest = (msg) ->
  console.log "Server received #{msg} \n"

  new Promise (resolve) ->
    "bar"

  setTimeout () ->
    Promise.resolve()
  , 2000

  Promise

handleRequest "foo"
.then (msg) ->
  console.log msg

我不知道我在哪里弄乱它,因为Bluebird的创建new Promise的文档似乎只是一个具有解析/拒绝功能的函数。

如果不使用promisify,我无法找到任何类似的promises创建方法。

EventEmitters可以做到这一点,但我真的需要在大版本中使用promises。 还有一些其他代码使用了相同的流程:一个创建/返回延迟的函数,它将在某个阶段被解析/拒绝。

非常感谢你! :) 整个上午我一直在努力。

Server received foo 

TypeError: Object function Promise(resolver) {
    if (typeof resolver !== "function") {
        throw new TypeError("the promise constructor requires a resolver function");
    }
    if (this.constructor !== Promise) {
        throw new TypeError("the promise constructor cannot be invoked directly");
    }
    this._bitField = 0;
    this._fulfillmentHandler0 = void 0;
    this._rejectionHandler0 = void 0;
    this._promise0 = void 0;
    this._receiver0 = void 0;
    this._settledValue = void 0;
    this._boundTo = void 0;
    if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
} has no method 'then'

1 个答案:

答案 0 :(得分:0)

通过Google搜索错误,我看到了Bluebird文档的this页面。 所以我理解代码的异步部分是promise本身的解析,因此重写代码如下所示解决了这个问题:

Promise = require 'bluebird'

handleRequest = (msg) ->
  new Promise (resolve) ->
    setTimeout () ->
      resolve "bar"
    , 2000

handleRequest "foo"
.then (msg) ->
  console.log msg