You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
Sven Slootweg d82d62aed6 Initial version 3 months ago
README.md Initial version 3 months ago
example.js Initial version 3 months ago
index.js Initial version 3 months ago
package.json Initial version 3 months ago

README.md

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.