1

In code bellow, I would like that somehow changed commented part should be able to set document's body instead of "this.body = 'test';" (it still should be Promise solution).

'use strict'

var app = require('koa')(),
    router = require('koa-router')();

router.get('/', function *(next) {
    this.body = 'test';
    // var promise = new Promise(function(resolve, reject) {
    //   resolve("test");
    // });
    // promise.then(function(res){
    //   this.body = res;
    // })
});

app
  .use(router.routes())

app.listen(8000);

The problem is that "this" inside a Promise is not referred to "the right one".

olegzhermal
  • 799
  • 10
  • 26
  • document's body is client side you should use a template engine and send the variable to be changed to the layout where the `` is. – michelem Mar 31 '16 at 15:47

1 Answers1

3

This sounds quite like a duplicate of How to access the correct `this` context inside a callback? (with the solution being using an arrow function for the callback), but actually you don't need those callbacks at all with koa (and co). You can just yield the promise!

router.get('/', function*(next) {
    this.body = 'test';
    var promise = Promise.resolve("test");
    var res = yield promise;
    this.body = res;
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375