My connections manager is expected to receive connect requests nondeterministically and to handle them in sequence.
How can asynchronous operations be queued such that they are handled later?
I'm not sure of what objects to place in a queue.
Here is my beginner's attempt. Thanks for any help!
class RequestQueue {
private _requests = [];
constructor() {}
public add( rq: any ) {
this._requests.unshift(rq);
}
public remove() {
return this._requests.pop();
}
}
class ConnectionManager {
private requestQueue;
private connecting: boolean = false;
constructor() {
this.requestQueue = new RequestQueue();
}
// ConnectionManager is expected to receive connection requests
// nondeterministically and to handle them in sequence.
public connect(id: string) {
if (!this.connecting) {
this.connecting = true;
return this.asyncConnect(id)
.then(
(result) => result,
(err) => err
)
.then( () => {
this.connecting = false;
if (this.requestQueue.length > 0) {
return this.requestQueue.remove();
}
});
} else {
// how do I queue a someAsyncOp for later?
}
}
private asyncConnect(id: string) : Promise<any> {
return new Promise( (resolve, reject) => {
console.log('begin connect to ', id);
setTimeout(() => {
console.log('end connect to ', id);
resolve();
}, 3000);
});
}
}
function makeConnections() {
const connectionManager = new ConnectionManager();
connectionManager.connect('A');
connectionManager.connect('B');
connectionManager.connect('C');
connectionManager.connect('D');
}
makeConnections();