0

I have an app that uses koa.js, and for context I am in the process of interfacing an external system that doesn't strictly follow request/responses pattern. IE. after a "request", it may or may not answer.

I am able to match my requests to these responses, but then I am unable to put that into the koa.js response :

r.get('/...', *function() {

    // (1) cannot yield since it will block and never call (2) ?
    callbacks.storeCb(howToMatchAnEventualResponse, function(err, resp) {  // may never get called depending about how the external system answers
        console.log("I should answer the http req now"); // how to answer the request from here ?
    });

    // has to be done after storingCb, this may or may not trigger the callback above
    externalSystem.sendMessage(msg); // (2)

    // something similar will have to be done in the callback instead
    this.body = {
        success : true,
        response : ''
    };

});

So my question is, how do I answer the http request using koa in my callback (or something similar), and how can I send an empty answer when the callback is not called (ie. after a delay maybe) ?

I am guessing that I am looking for something similar to Promise.race(), but for koa, so using yield.

nha
  • 17,623
  • 13
  • 87
  • 133

1 Answers1

0

Well in the end I was able to use bluebird's Promise.race().

I would still be interested into a solution using generators.

nha
  • 17,623
  • 13
  • 87
  • 133
  • 1
    The generator abstraction in Koa is mostly used to simplify route logic (i.e. handling a request) rather than the abstraction you have to use to solve every problem (which it can't). The "Koa Way" really is to wrap your more complex async logic with functions that return a promise and then yielding them in your route (`Promise.race()` in your case). That way you keep complexity outside of routes but you also get to write simple callback-based async code when that's all you need to solve the problem. Think of generators as mostly a tool you use from your route handlers. – danneu Jan 07 '16 at 18:14
  • 1
    Two things: 1) `Promise.race` is in both ES2015 and Bluebird 2) Bluebird recommends using `BluebirdPromise.any` instead of `BluebirdPromise.race` because the former marks even a rejected promise as the "winner" http://bluebirdjs.com/docs/api/promise.race.html – Max Heiber Sep 03 '16 at 03:33