Maison > interface Web > js tutoriel > le corps du texte

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

Susan Sarandon
Libérer: 2024-10-18 14:52:02
original
365 Les gens l'ont consulté

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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!

source:php
Déclaration de ce site Web
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
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal