Tracking inflight operations
This code sample demonstrates how to use the inflight package to prevent the same asynchronous operation from being executed multiple times simultaneously. It uses a timeout to simulate an asynchronous operation and ensures that if the operation is already in progress, subsequent calls will not initiate a new one.
const inflight = require('inflight');
function asyncOperation(key, callback) {
if (inflight(key)) return;
inflight(key, callback);
// Perform the operation here
setTimeout(() => {
// Operation completed
inflight(key, null);
callback();
}, 1000);
}
asyncOperation('operation1', () => console.log('Operation 1 completed.'));
asyncOperation('operation1', () => console.log('Operation 1 is already in flight.'));