Introducing Promise-Funnel – Hacker Noon

How to use it

Here’s how you might use it with a database application that needs to connect before sending any queries.

You can see that queries were immediately corked and were only uncorked when the database connection was successful. This means that the service can immediately accept requests, but it won’t execute any queries until the database connection happens!

Now let’s look at the authentication example that I mentioned earlier.

Every five minutes the user is logged in again. While login is happening every user request would fail. So instead of letting that happen, we’ve corked the fetch requests until login is complete. Now the user won’t be stopped by authentication.. although they might be delayed!

In case you’re wondering, createFunnel will create a new funnel instance each time. This means that you can safely funnel different actions separately.

Using your own Promises

Not every environment has Promises natively. If you want to use a library like Bluebird with promise-funnel, you can!

The Promise Part

So far we haven’t really seen how a Promise is used by this library. A function won’t execute immediately when both the function is wrapped and the funnel is corked. A Promise is returned instead. It will resolve or reject only when the funnel is uncorked.

The code snippet above should show that uncorking the funnel will resolve the promise that was returned by the wrapped function.

This means that any functions that uses await on a wrapped function or uses .then().catch() on a wrapped function will not continue until the funnel uncorks.

read original article here