node.js - 如何在 Promise 中设置 body?

标签 node.js promise koa document-body koa-router

在下面的代码中,我希望以某种方式更改的注释部分应该能够设置文档的正文而不是“this.body = 'test';” (它仍然应该是 Promise 解决方案)。

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

问题在于 Promise 中的“this”并未引用“正确的”。

最佳答案

这听起来很像 How to access the correct `this` context inside a callback? 的重复项(解决方案是使用箭头函数进行回调),但实际上 koa (和 co)根本不需要这些回调。你可以兑现 promise !

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

关于node.js - 如何在 Promise 中设置 body?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36337940/

相关文章:

node.js - 错误 : GoogleMapsAPI is not defined for node-googlemaps

javascript - 使用 Passport : How to flash a message if a field is missing? 进行 Node.js 身份验证

javascript - 推迟并没有解决

ember.js - Ember - 异步计算属性或观察者?

node.js - 环回 - "next()"未在 "beforeRemote"中的正确时间触发?

node.js - Express 中的路由可以用循环声明吗?

javascript - Bluebird Promise 可以在 node.js 中与 redis 一起使用吗?

node.js - koa-views nunjucks : Error: template not found: master

javascript - 如何使用正则表达式来匹配 ctx​​.url,如 koa 中的 ''/?id=xxx '' and "/"?

typescript - Koa + typescript : Property 'body' does not exist on type Request