メソッドが単一の引数を持つノード「errback」である場合、パラメーターなしで解決されるか、代わりに渡されたものthen
で拒否されます。err
約束の場合は、 でキャッチする.error
か、 でキャッチを使用できますPromise.OperationalError
。
簡単なアプローチを次に示します。
function getConnection(){
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
return connection.connectAsync().return(connection); // <- note the second return
}
getConnection().then(function(db){
return db.queryAsync(....);
}).error(function(){
// could not connect, or query error
});
これが接続を管理するためのものである場合-私は使用しますPromise.using
-ここにAPIのサンプルがあります:
var mysql = require("mysql");
// uncomment if necessary
// var Promise = require("bluebird");
// Promise.promisifyAll(mysql);
// Promise.promisifyAll(require("mysql/lib/Connection").prototype);
// Promise.promisifyAll(require("mysql/lib/Pool").prototype);
var pool = mysql.createPool({
connectionLimit: 10,
host: 'example.org',
user: 'bob',
password: 'secret'
});
function getSqlConnection() {
return pool.getConnectionAsync().disposer(function(connection) {
try {
connection.release();
} catch(e) {};
});
}
module.exports = getSqlConnection;
これにより、次のことが可能になります。
Promise.using(getSqlConnection(), function(conn){
// handle connection here, return a promise here, when that promise resolves
// the connection will be automatically returned to the pool.
});