async-status
v1.1.0
Published
A standardized way to express asynchronous state in a synchronous manner.
Readme
Table of Contents 📋
Installation 📦
# with npm
npm install --save async-status
# with yarn
yarn add async-statusThis assumes that you’re using a module bundler like Webpack to consume ES6 or CommonJS modules.
Concept 💡
The goal of this package is to provide a unified and standardized representation of asynchronous status.
It helps to integrate other libraries that translate asynchronous state to synchronous state
(for example Redux).
Instead of using different flags like isLoading, isPending, hasError, this library represents asynchronous status
as a one-variable - status.
There are 4 possible statuses:
AsyncStatus.IDLE⚫️ - means that nothing happens - it's the initial statusAsyncStatus.PENDING⏳ - means that async action is pendingAsyncStatus.RESOLVED✅ - means that async action has been successfully finishedAsyncStatus.REJECTED❌ - means that an error occurred during async action
There are no constraints about transitions between given statuses.
To give a better understanding of the relationship between AsyncStatus and asynchronous code let's try with real code:
import AsyncStatus from "async-status";
const state = {
status: AsyncStatus.IDLE
};
function fetchUsers() {
state.status = AsyncStatus.PENDING;
fetch("/api/user")
.then(response => response.json())
.then(data => {
state.data = data;
state.status = AsyncStatus.RESOLVED;
})
.catch(error => {
state.error = error;
state.status = AsyncStatus.REJECTED;
});
}
fetchUsers();As you can see, you don't have to introduce any boolean flags like isPending 👌
API reference 📖
The status is a primitive value - string or undefined.
AsyncStatus.IDLE = undefined;
AsyncStatus.PENDING = "PENDING";
AsyncStatus.RESOLVED = "RESOLVED";
AsyncStatus.REJECTED = "REJECTED";AsyncStatus.all(...statuses: AsyncStatus[]): AsyncStatus
Combines many statuses into one status using an algorithm similar to Promise.all method.
Basically the algorithm is:
- if statuses list is empty, result = IDLE
- if one of the statuses is equal REJECTED, result = REJECTED
- if one of statuses is equal PENDING, result = PENDING
- if all statuses equal RESOLVED, result = RESOLVED
- in other cases, result = IDLE
isAsyncStatus(candidate: any): candidate is AsyncStatus
Checks if a given candidate is an AsyncStatus (means that it's equal undefined or 'PENDING' or 'RESOLVED' or 'REJECTED')
Typings 📐
If you are using TypeScript, typings are provided in the npm package. This library doesn't provide Flow typings.
License
MIT
