使用bluebird,您可以使用Promise.promisifyAll
(和Promise.promisify
)将Promise ready方法添加到任何对象。
var Promise = require('bluebird');
// Somewhere around here, the following line is called
Promise.promisifyAll(connection);
exports.getUsersAsync = function () {
return connection.connectAsync()
.then(function () {
return connection.queryAsync('SELECT * FROM Users')
});
};
像这样使用:
getUsersAsync().then(console.log);
要么
// Spread because MySQL queries actually return two resulting arguments,
// which Bluebird resolves as an array.
getUsersAsync().spread(function(rows, fields) {
// Do whatever you want with either rows or fields.
});
添加处置器
Bluebird支持许多功能,其中之一是处理程序,通过Promise.using
and 结束连接后,它可以让您安全地处理连接Promise.prototype.disposer
。这是我的应用程序中的一个示例:
function getConnection(host, user, password, port) {
// connection was already promisified at this point
// The object literal syntax is ES6, it's the equivalent of
// {host: host, user: user, ... }
var connection = mysql.createConnection({host, user, password, port});
return connection.connectAsync()
// connect callback doesn't have arguments. return connection.
.return(connection)
.disposer(function(connection, promise) {
//Disposer is used when Promise.using is finished.
connection.end();
});
}
然后像这样使用它:
exports.getUsersAsync = function () {
return Promise.using(getConnection()).then(function (connection) {
return connection.queryAsync('SELECT * FROM Users')
});
};
一旦promise用值解析(或使用拒绝Error
),这将自动终止连接。