Sven Slootweg d82d62aed6 | 5 months ago | |
---|---|---|
README.md | 5 months ago | |
example.js | 5 months ago | |
index.js | 5 months ago | |
package.json | 5 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.