0

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
akc42
  • 4,893
  • 5
  • 41
  • 60
  • This exact code works for me with the following: const x = new HTTP(); x.request({}, () => {}); x.requestEnd('{ "hello": true }'); x.requestEndDone(); — gives: About to resolve params { hello: true } End Promise with { hello: true } (tested on node 7.7, 7.8 and 7.9) – Brendan Molloy Apr 13 '17 at 16:29
  • I had forgotten about this SO question. I think the problem stems from some timing issues and the fact that there is only one promise kept at anyone time. I believe I might have overwrote one promise with another before the first was resolved. I rewrote it with an array of promises and my problem went away – akc42 Apr 16 '17 at 06:07

0 Answers0