2016-11-15 40 views
1

此問題出現在以下問題中:node.js: how to return a value of a callback function?Bluebird.Promisify - 如何創建一個承諾鏈正確?

我決定使用Bluebird.promisify編寫上一個問題中的代碼。這是我寫的:

var express = require('express') 
var app = express() 
var MongoClient = require('mongodb').MongoClient; 
var db = require('./db.js') 
var Promise = require('bluebird'); 

app.get('/', function(req, res){ 
    var result = Promise.promisify(db.get_document); 
    result().then(function(doc) { 
     res.send(doc); 
     console.log("end"); 
    }); 
}); 

app.listen(3000, function(req, res) { 
    console.log("Listening on port 3000"); 
}); 

function get_document() { 
    var connect = Promise.promisify(MongoClient.connect); 
    connect(url).then(function(err,db) { 
    var col = db.collection('myinterviews'); // !!! ERROR!!! 'db' undefined 
    return col.find().toArray 
    }).then(function (err, docs) { 
    db.close(); 
    return docs[0].name; 
    }); 
}; 

行:

var col = db.collection('myinterviews');

提供錯誤消息:

"Unhandled rejection TypeError: Cannot read property 'collection' of undefined."

功能MongoClient.connect接受有兩個參數的回調函數,那麼,爲什麼'db'undefined?

+0

我沒有看到MongoClient在任何地方定義,這可能是問題。 url定義在哪裏。 – anwerj

+0

我複製代碼時錯過了。我編輯了原文。 – CrazySynthax

+0

你甚至在哪裏調用'get_document'? – Bergi

回答

0

承諾不會通過錯誤,並導致相同的方法。您必須添加catch才能獲得err。

此外,您承諾的方法需要回調並將其與第一個參數一起作爲錯誤和其他結果調用。

var express = require('express') 
var app = express() 
var MongoClient = require('mongodb').MongoClient; 
var Promise = require('bluebird'); 

app.get('/', function(req, res){ 

    var result = Promise.promisify(get_document); 
    result().then(function(doc) { 
     res.send(doc); 
     console.log("end"); 
    }).catch(function(err){ 
     console.log(err); 
     res.status(500).send(err.toString()); 
    }); 
}); 

app.listen(3000, function(req, res) { 
    console.log("Listening on port 3000"); 
}); 

function get_document (callback) { 
    return Promise.promisify(MongoClient.connect)(YOUR_URL) 
    .then(function(db){ 
     return db.collection(YOUR_COLLECTION).find().toArray(); 
    }) 
    .then(function (docs) { 
     return callback(null, docs[0].name); 
    }).catch(function(err){ 
     return callback(err); 
    }); 
}; 
+0

現在,我得到一個「db.close()」錯誤:「db沒有定義」 – CrazySynthax

+0

這是因爲db在第二個函數中不存在。那是js 101. – anwerj

+0

好的。所以當我刪除行「db.close」時,docs [0] .name不會傳輸到res.send(doc)。 – CrazySynthax