DEV Community

Apoorv Saxena
Apoorv Saxena

Posted on

Introducing AsyncResolver.js: Resolve async subscribed decisions

PubSub architecture implements a disjointed paradigm where subscribers just listen when an event is published. There are situations where we want to maintain multiple listeners/subscribers of an event, though want to act on the basis of how subscribers react.

Example

Let's consider a case where there are several components on a webpage, whose state can be changed by the user and we make every component to subscribe as listener to listen to a page transition so that we can check if a user is trying to move without saving data.

Now, when a user clicks on a link, we publish an event mentioning of the transition of user from the page, though we want to ask every listener (or component) if user has made any changes to their state and is moving without saving them.

In case there are any unsaved changes in any of the component, then we cancel the transition and instead display an information dialog to the user asking him to save information before proceeding further.

AsyncResolver.js Asynchronously resolve subscribed decisions

AsyncResolver.js is the solution for this need, it's an amalgamation of pub sub architecture and promises to provide decision making capability in asynchronous environment.

Install

### NPM
npm install async-resolver

### Yarn
yarn add async-resolver
Enter fullscreen mode Exit fullscreen mode

Usage

const AsyncResolver = require('async-resolver');

let resolver = new AsyncResolver();
resolver.subscribe('locationChange', () => Promise.resolve());
resolver.subscribe('locationChange', () => Promise.reject());

resolver
    .publish('locationChange', {
        promiseMethod: 'any'
    })
    .then(() => console.log('location change allowed'))
    .catch(() => console.log('location change denied'))
Enter fullscreen mode Exit fullscreen mode

For details, checkout AsyncResolver.js repo on Github

Top comments (0)