【问题标题】:Simple Q Promises Node Example简单的 Q Promises 节点示例
【发布时间】:2013-07-04 01:26:54
【问题描述】:

我一般都在尝试围绕 Q 库/promises 进行思考,以便我可以在我的节点应用程序中实现它,但是我很难找到足够简洁和具体的东西来快速开始。

有人可以帮我使用 Q 的 promise 库将这段代码翻译成异步模式吗?

// # For those new to coffeescript

// # '(params) ->' === 'function (params) {}' in coffeescript
// # '@' === 'this' in coffeescript


// # NPM
Q = require 'q'

// # Database class
module.exports = class Database

  constructor: () -> 
    // # mongoose
    @mongoose = require('mongoose')  

    // # Make database connection
    @connect_database()

  connect_database: () ->
    try
      @mongoose.connect('mongodb://127.0.0.1:27017/database')
      return 'Database connected'.green
    catch e
      return ('Database connection error: ' + e.toString()).red

一旦我看到一些直接适用的东西,我认为将我的应用程序的其余部分转换为这种模式会容易得多。

【问题讨论】:

    标签: javascript node.js coffeescript promise q


    【解决方案1】:

    所以基本上你想返回 dfd.promise 然后在连接到数据库后解决或拒绝它。

    Q = require 'q'
    
    connect: () ->
     # Create deferred object
     dfd = Q.defer()
    
     # Attempt to connect
     try
      @mongoose.connect(...)
      # Resolve deferred object
      dfd.resolve('Database connected')
    
     catch e
      # Reject deferred with error object
      dfd.reject(e)
    
     # Return promise immediately
     dfd.promise
    

    现在,当您运行connect 方法时,您将获得一个可以绑定到.then.fail 方法的promise 对象

    db.connect()
     .then(msg) ->
     .fail(e) ->
    

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 1970-01-01
      • 2013-07-01
      • 2017-12-05
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      相关资源
      最近更新 更多