mongodb 原生的承诺

Promisification of mongodb native

我正在尝试使用 bluebird 和 mongodb,但出现错误。

var Promise = require("bluebird")
var MongoDB = require("mongodb")
Promise.promisifyAll(MongoDB)

return MongoDB.connectAsync(process.env.MONGO_URL).then(function(db){
  var collection = db.collection('queue')
  return collection.find().toArray().then(function(docs){
    console.log(docs)
  })
}).catch(function(e){
  console.log(e.message)
  throw e
})

我收到此错误:

Unhandled rejection Error
    at Object.<anonymous> (/Users/thomas/Desktop/project/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:42:24)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:428:10)
    at Module.load (module.js:335:32)
    at Function.Module._load (module.js:290:12)
    at Module.require (module.js:345:17)
    at require (module.js:364:17)
    at Object.<anonymous> (/Users/thomas/Desktop/project/node_modules/mongodb/node_modules/mongodb-core/index.js:2:17)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:428:10)
    at Module.load (module.js:335:32)
    at Function.Module._load (module.js:290:12)
    at Module.require (module.js:345:17)
    at require (module.js:364:17)
    at Object.<anonymous> (/Users/thomas/Desktop/project/node_modules/mongodb/index.js:2:12)
    at Module._compile (module.js:410:26)

如果你 catchthrow e.message 你会看到这个:

Unhandled rejection Error: callback is mandatory
    at Object.ensureErrorObject (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/util.js:226:20)
    at Promise._rejectCallback (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:416:22)
    at Promise._settlePromiseFromHandler (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:460:17)
    at Promise._settlePromiseAt (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:530:18)
    at Promise._settlePromises (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:646:14)
    at Async._drainQueue (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/async.js:132:16)
    at Async._drainQueues (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/async.js:142:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/async.js:16:14)
    at processImmediate [as _immediateCallback] (timers.js:357:17)

必须使用.toArrayAsync()

var Promise = require("bluebird")
var MongoDB = require("mongodb")
Promise.promisifyAll(MongoDB)

return MongoDB.connectAsync(process.env.MONGO_URL).then(function(db){
  var collection = db.collection('queue')
  return collection.find().toArrayAsync().then(function(docs){
    console.log(docs)
  })
}).catch(function(e){
  console.log(e.message)
  throw e
})