deepwiki-lab
Relevant source files
  • test.js

Usage Examples

Basic Usage

p-defer is a utility for working with promises. It allows you to defer the execution of a function until a promise is settled. This can be useful in a variety of scenarios, such as when you need to perform an action after a promise has been resolved or rejected.

Example Usage in test.js

const defer = require('p-defer');

// Create a new promise
const p = new Promise((resolve, reject) => {
  // Simulate some asynchronous operation
  setTimeout(() => {
    resolve('Hello, World!');
  }, 2000);
});

// Create a new defer object
const { promise, resolve, reject } = defer();

// Use the defer object to execute a function after the promise is settled
promise.then(() => {
  console.log('Promise resolved:', resolve());
}).catch((error) => {
  console.error('Promise rejected:', error);
});

// Resolve the promise manually
setTimeout(() => {
  resolve(p);
}, 1000);

Using p-defer with async/await

p-defer can also be used with async/await syntax to simplify the code.

const defer = require('p-defer');

// Create a new promise
const p = new Promise((resolve, reject) => {
  // Simulate some asynchronous operation
  setTimeout(() => {
    resolve('Hello, World!');
  }, 2000);
});

// Create a new defer object
const { promise, resolve, reject } = defer();

// Use async/await to wait for the promise to settle
async function main() {
  try {
    const result = await promise;
    console.log('Promise resolved:', result);
  } catch (error) {
    console.error('Promise rejected:', error);
  }
}

// Resolve the promise manually
setTimeout(() => {
  resolve(p);
}, 1000);

main();

Sources:

test.js