Monday, July 18, 2022

[FIXED] How to set body inside a Promise?

Issue

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".


Solution

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;
});


Answered By - Bergi
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.