Maison  >  Article  >  interface Web  >  Qu'est-ce que le modèle Promise Disposer et comment fonctionne-t-il ?

Qu'est-ce que le modèle Promise Disposer et comment fonctionne-t-il ?

Susan Sarandon
Susan Sarandonoriginal
2024-10-18 14:52:02277parcourir

What is the Promise Disposer Pattern and How Does it Work?

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:

<code class="javascript">function getDb() {
  return myDbDriver.getConnection();
}

var users = getDb().then(function (conn) {
  return conn.query("SELECT name FROM users").finally(function (users) {
    conn.release();
  });
});</code>

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:

<code class="javascript">withResource(function (resource) {
  return fnThatDoesWorkWithResource(resource); // returns a promise
}).then(function (result) {
  // resource disposed here
});</code>

Applying It to Your Code

By refactoring your code into the disposer pattern:

<code class="javascript">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();
  });
}</code>

You can now rewrite your previous code as:

<code class="javascript">withDb(function (conn) {
  return conn.query("SELECT name FROM users");
}).then(function (users) {
  // connection released here
});</code>

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn