Inspired by Operation and OperationQueue classes from Apple's Foundation framework for macOS, iOS, watchOS, and tvOS.
Universal package for the browser and node.js
with node:
npm install operationkit
with yarn:
yarn add operationkit
with cdn:
<script src="https://unpkg.com/operationkit/dist/operationkit.min.js"></script>
// then
window.operationkit
const {
Operation,
OpreationQueue,
BlockOperation,
GroupOperation,
OperationEvent,
QueueEvent,
QueuePriority
} = require('operationkit');
An abstract class that represents a single task.
const operation = new Operation();
const result = await operation.start();
The operation will execute only when all dependencies are resolved.
operation1.dependencies = [operation2];
operation1.start()
Console:
// operation2 started
// operation2 done
// operation1 started
// operation1 done
class ValidateTokenOperation extends Operation {
/**
* Method to implement to run custom task
* @override
* @returns {Promise}
*/
async run() {
let token = localStorage.getItem('token');
if (!token) {
const response = await axios('<refresh_token_api>');
token = reponse.data;
localStorage.setItem('token', token);
}
return token;
}
}
Now use it as a dependency for your API requests:
class ApiRequestOperation extends Operation {
constructor() {
this.dependencies = [new ValidateTokenOperation()]
}
}
You can now make all api requests of your app able to refresh the token by extending ApiRequestOperation
class DownloadDataOperation extends ApiRequestOperation {
async run() {
try {
const response = await axios.get('<some_api>');
return response.data;
} catch (e) {
this.cancel();
}
}
}
The run
function must always return a promise.
run() {
return new Promise((resolve, reject) => {
const response = await axios.get('<some_api>');
resolve(response.data);
})
}
or simply use async keyword when overriding the function.
async run() {
const response = await axios.get('<some_api>');
return response.data
}
class DownloadDataOperation extends Operation {
/**
* @override
*/
async run() {
try {
const response = await axios.get('<some_api>');
return response.data;
} catch (e) {
this.cancel();
}
}
}
TO NOTE: you must always return the result from the async function or Promise.resolve. You will have access to the result from the the result property or from resolving your promise.
const downloadOperation = new DownloadDataOperation();
// result is returned from your promise here
const data = await new DownloadDataOperation();
// and the same result is available from
downloadOperation.result;
const validateToken = new ValidateTokenOperation();
const getUsersApi = new GetUsersApi();
getUsersApi.dependencies = [validateToken];
getUsersApi.completionCallback = operation => {
// operation.result;
};
getUsersApi.start()
.then(result => { ... })
.catch(e => { ... });
Or set the dependency directly in the subclass:
class GetUsersApi extends Operation {
constructor() {
this.dependencies = [new ValidateTokenOperation()];
}
}
- OperationEvent.START Operation has started to run the task
- OperationEvent.READY Operation is ready to be executed
- OperationEvent.DONE Operation is finished running the task
- OperationEvent.CANCEL Operation was cancelled
- OperationEvent.ERROR An error occured while running the task
apiOperation.on(OperationEvent.START, (operation) => {
console.log(operation);
})
A queue orchestrates the execution of operations. An operation queue executes its queued Operation objects based on their priority and readiness*.
const operationQueue = new OperationQueue();
const operation1 = new ApiOperation();
const operation2 = new ApiOperation();
operationQueue.addOperations([operation1, operation2]);
operationQueue.maximumConcurrentOperations = 2;
Console:
// operation1 started
// operation2 started
// operation1 done
// operation2 done
Specify the relative ordering of operations that are waiting to be started in an operation queue.
QueuePriority.veryHigh
QueuePriority.high
QueuePriority.normal
QueuePriority.low
QueuePriority.veryLow
These constants let you prioritize the order in which operations execute:
const getCacheData = new GetCacheDataOperation();
getCacheData.queuePriority = QueuePriority.high;
const downloaHighRestImage = new DownloaHighRestImageOperation();
getCacheData.queuePriority = QueuePriority.normal;
operationQueue.addOperations([getCacheData, downloaHighRestImage]);
Console:
// getCacheData started
// getCacheData done
// downloaHighRestImage started
// downloaHighRestImage done
const blockOperation6 = new BlockOperation(6, async () => {
const response = await axios.get('https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22');
const data = response.data;
return data;
});
const operation = new DownloadDataOperation(1);
const operation2 = new DownloadDataOperation(2);
const operation3 = new DownloadDataOperation(3);
const operation4 = new TimeOutOperation(4, 2000);
const operation5 = new TimeOutOperation(5, 1000);
const operation7 = new TimeOutOperation(7, 8000);
const operation8 = new TimeOutOperation(8, 1500);
operation.dependencies = [operation2, operation7];
operation2.dependencies = [operation4, operation8];
operation3.dependencies = [operation, operation5, operation2];
operation4.dependencies = [operation5, blockOperation6];
operation5.dependencies = [blockOperation6];
operation8.dependencies = [operation7];
const operationQueue = new OperationQueue();
operationQueue.maximumConcurrentOperations = 10;
operationQueue.completionCallback = () => {
console.log('queue done');
};
operationQueue.addOperations([operation3]);
- OperationEvent.DONE OperationQueue has finished running all operations
- OperationEvent.PAUSED OperationQueue has paused
- OperationEvent.RESUMED OperationQueue has resumed
queue.on(OperationEvent.PAUSED, (operationQueue) => {
console.log(operationQueue);
})
A helper class that accepts a function which will be exexuted as the operation's task.
const operation = new BlockOperation(async (op) => {
const data = await api.get();
...
return data;
});
const result = await operation.start()
console.log(result) // 'my operation result'
You have acces to the operation in the function:
const operation = new BlockOperation(async (op) => {
console.log(op === operation);
});
Group multiple operations and return the result of each operation when they are all resolved.
const groupOperation = new GroupOperation();
groupOperation.addOperation(new GetUsersApi());
groupOperation.addOperation(new GetPostsApi());
const [users, posts] = await groupOperation.start();
QueuePriorities are also considered when using GroupOperation.
npm run test
npm run test-coverage
npm run build
npm run docs