Ivan Stoyanov
Ivan Stoyanov

Reputation: 5482

Koa GET return result immediately to the client and do something afterward

I'm writing an io.js and Koa API and I have a GET route that I use to pass data to the API and return OK to the user immediately. Basically I don't care about the result that the GET request will return, I just want to pass the data. This is why I want to return "OK" to the client then he makes the GET request as soon as possible and then process the data from the request.

My code so far is as follows:

app.use(route.get("/passData", function*(){
    this.body = "OK";
    yield doSomeWork(this.query);
});

function *doSomeWork(query){
   // do work
   // the code below should be triggered when the client receives the OK message
}

Is there a way to do this?

Upvotes: 0

Views: 201

Answers (1)

user663031
user663031

Reputation:

You do not want to yield on doSomeWork--that tells Koa to wait, which is exactly what you do not want.

app.use(route.get("/passData", function*(){
    this.body = "OK";
    doSomeWork(this.query); // REMOVE YIELD
});

Since doSomeWork is just a plain old asynchronous function now, it's shouldn't be a generator. (If you leave the * there, you'll be calling a generator, which does absolutely nothing other than to create an iterator which will then be thrown away.)

function doSomeWork(query){ // REMOVE ASTERISK
   // do work
   // the code below should be triggered when the client receives the OK message
}

Upvotes: 2

Related Questions