Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

capture-promise

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

capture-promise

Small utility function for safe evaluation of async functions, capturing synchronous outcomes as well

latest
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

capture-promise

The problem: you want to call a user-supplied callback and expect it to return a Promise, but you don't know if it might throw or return synchronously, and you want to make sure that you are dealing with a Promise.

This solves that problem by capturing all outcomes of a given callback - whether they are synchronous or asynchronous - and always giving you a Promise that resolves or rejects accordingly, much like you would expect an async function or .then to do.

Roughly analogous to Promise.try.

Example

A runnable version of this example is included in the package as example.js.

"use strict";

const capturePromise = require("capture-promise");

function dubiousUserSuppliedCallback() {
	if (Math.random() < 0.5) {
		return Promise.resolve(true);
	} else {
		throw new Error(`Oops, this is synchronously thrown!`);
	}
}

(async function () {
	let promise = capturePromise(() => dubiousUserSuppliedCallback());
	console.log(promise); // Always prints a Promise, regardless of whether the callback throws or not
	await promise; // ... and we can await it like any Promise!
})();

API

capturePromise(wrapper)

  • wrapper: A callback which calls the dubious function. Note that you cannot directly pass the dubious function (eg. user-supplied callback)! You must wrap it in your own callback, like in the example code.

Returns: A Promise that resolves if the callback returned a resolved Promise or synchronous value; or rejects if the callback returned a rejected Promise or threw a synchronous error.

Keywords

promises

FAQs

Package last updated on 18 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts