What is @open-draft/deferred-promise?
@open-draft/deferred-promise is a utility library that provides a way to create and manage deferred promises. This can be particularly useful in scenarios where you need to create a promise and resolve or reject it at a later time, outside of the initial promise executor function.
What are @open-draft/deferred-promise's main functionalities?
Creating a Deferred Promise
This feature allows you to create a deferred promise that can be resolved or rejected at a later time. The code sample demonstrates creating a deferred promise, resolving it after a timeout, and then using the promise in an async function.
const { DeferredPromise } = require('@open-draft/deferred-promise');
const deferred = new DeferredPromise();
// You can resolve or reject the promise later
setTimeout(() => {
deferred.resolve('Resolved value');
}, 1000);
// Use the promise
async function main() {
const result = await deferred;
console.log(result); // 'Resolved value'
}
main();
Handling Rejection
This feature allows you to handle the rejection of a deferred promise. The code sample demonstrates creating a deferred promise, rejecting it after a timeout, and then handling the rejection in an async function.
const { DeferredPromise } = require('@open-draft/deferred-promise');
const deferred = new DeferredPromise();
// You can resolve or reject the promise later
setTimeout(() => {
deferred.reject(new Error('Something went wrong'));
}, 1000);
// Use the promise
async function main() {
try {
const result = await deferred;
} catch (error) {
console.error(error.message); // 'Something went wrong'
}
}
main();
Other packages similar to @open-draft/deferred-promise
p-defer
p-defer is a similar utility that allows you to create deferred promises. It provides a simple API to create a deferred promise and resolve or reject it later. Compared to @open-draft/deferred-promise, p-defer is more widely used and has a more established presence in the npm ecosystem.
deferred
deferred is another package that provides deferred promise functionality. It offers a similar API to @open-draft/deferred-promise but includes additional utilities for working with promises. It is a more feature-rich alternative but may be more complex to use.
Deferred Promise
The DeferredPromise
class is a Promise-compatible abstraction that defers resolving/rejecting promises to another closure. This class is primarily useful when one part of your system establishes as promise but another part of your system fulfills it.
This class is conceptually inspired by the createDeferredPromise()
internal utility in Node.js. Unlike the Node.js implementation, however, DeferredProimse
extends a native Promise
, allowing the consumer to handle deferred promises like regular promises (no .promise
instance nesting).
Getting started
npm install @open-draft/deferred-promise
Documentation
Class: DeferredPromise
new DefferedPromise()
Creates a new instance of a deferred promise.
import { DeferredPromise } from "@open-draft/deferred-promise";
const promise = new DeferredPromise();
Unlike the regular Promise
, a deferred promise does not accept the callback function. Instead, you should use .resolve()
and .reject()
to resolve and reject the promise respectively.
A deferred promise is fully compatible with the native Promise
, which means you can pass it to the consumers that await a regular Promise
as well.
deferredPromise.state
<"pending" | "resolved" | "rejected">
Default: "pending"
const promise = new DeferredPromise();
console.log(promise.state);
promise.resolve();
console.log(promise.state);
deferredPromise.result
Returns the value that has resolved the promise. If no value has been provided to the .resolve()
call, undefined
is returned instead.
const promise = new DeferredPromise();
promise.resolve("John");
console.log(promise.result);
deferredPromise.rejectionReason
Returns the reason that has rejected the promise. If no reason has been provided to the .reject()
call, undefined
is returned instead.
const promise = new DeferredPromise();
promise.reject(new Error("Internal Server Error"));
console.log(promise.rejectionReason);
deferredPromise.resolve()
Resolves the deferred promise with a given value.
function startServer() {
const serverReady = new DeferredPromise();
new http.Server().listen(() => {
serverReady.resolve("http://localhost:8080");
});
return serverReady;
}
startServer().then((address) => {
console.log('Server is running at "%s"', address);
});
deferredPromise.reject()
Rejects the deferred promise with a given reason.
function createBroadcast() {
const runtimePromise = new DeferredPromise();
receiver.on("error", (error) => {
runtimePromise.reject(error);
});
return runtimePromise;
}
deferredPromise.finally()
Attaches a callback that executes when the deferred promise is settled (resolved or rejected).
const channelReady = new DeferredPromise();
channelReady.finally(async () => {
await channel.close();
});