Understanding the Promise Disposer Pattern
You've encountered the promise disposer pattern in your code, but its purpose remains elusive. This article aims to clarify the concept and demonstrate its application.
Problem Overview
In your code snippet:
function getDb() {
return myDbDriver.getConnection();
}
var users = getDb().then(function (conn) {
return conn.query("SELECT name FROM users").finally(function (users) {
conn.release();
});
});
You face the issue of potential resource leaks if you neglect to release the database connection after each getDb call. This can lead to system freezing if resource limits are exceeded.
Introducing the Disposer Pattern
The promise disposer pattern establishes a strong connection between a code scope and the resource it owns. By binding the resource to the scope, you ensure its prompt release when the scope concludes, eliminating the risk of oversight. This pattern bears similarities to C#'s using, Python's with, Java's try-with-resource, and C 's RAII.
Pattern Structure
The disposer pattern follows a specific structure:
withResource(function (resource) {
return fnThatDoesWorkWithResource(resource); // returns a promise
}).then(function (result) {
// resource disposed here
});
Applying It to Your Code
By refactoring your code into the disposer pattern:
function withDb(work) {
var _db;
return myDbDriver.getConnection().then(function (db) {
_db = db; // keep reference
return work(db); // perform work on db
}).finally(function () {
if (_db) _db.release();
});
}
You can now rewrite your previous code as:
withDb(function (conn) {
return conn.query("SELECT name FROM users");
}).then(function (users) {
// connection released here
});
Ensure that the resource is released within the finally block to guarantee proper disposal.
Real-World Examples
Notable examples of the disposer pattern in practice include Sequelize and Knex (Bookshelf's query builder). Its applications extend to managing complex asynchronous processes, such as showing and hiding loading indicators based on the completion of multiple AJAX requests.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3