PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label koa-router. Show all posts
Showing posts with label koa-router. Show all posts

Monday, July 18, 2022

[FIXED] How to set body inside a Promise?

 July 18, 2022     document-body, koa, koa-router, node.js, promise     No comments   

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)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing