I am trying to mock up a but of an http2 request object in order to test my usage of it. I am now on node version 7.8.0, so thought I would try and make use of async and await to do things.
I have created a mocking class for http2 (although its called HTTP) as follows:-
class HTTP {
constructor() {
this.version = HTTP.version + 1;
HTTP.version = this.version;
}
request(options, callback) {
let self = this;
this.callback = callback;
this.options = options;
this.endPromise = new Promise(resolve => {
self.endResolver = resolve;
});
return {end: this.requestEnd.bind(this)};
}
requestEnd(stringParams) {
let params = JSON.parse(stringParams);
if (this.endResolver) {
console.log('About to resolve params ', params);
this.endResolver(params);
}
}
async requestEndDone(params,status) {
let p2 = await this.endPromise;
console.log('End Promise with ', p2);
this.responseObject = new EventEmitter();
if (status) {
this.responseObject.statusCode = status;
} else {
this.responseObject.statusCode = 200;
}
this.callback(this.responseObject);
if (params) {
let body = JSON.stringify(params);
while (body.length > 0) {
let chunkSize = Math.floor(Math.random() * 20) + 10;
let chunk = body.substring(0,chunkSize);
body = body.substring(chunkSize);
this.responseObject.emit('data', chunk);
}
}
this.responseObject.emit('end');
}
}
HTTP.version = 0;
The important part is the this.endPromise
; When the code I am testing calls request.end
I resolve it, and then with the async function requestEndDone
my test script can await its completion knowing then a request callback has happened and can check the results of that.
The problem I have is slightly away from the main test thrust.
The two console.log
lines give inconsistent results.
About to resolve params { pid: 1234 }
End Promise with undefined
Is what is presented on the console. I thought await
returned the value the promise is resolved with, but in this case it doesn't.. Why?