【问题标题】:How to set body inside a Promise?如何在 Promise 中设置 body?
【发布时间】:2016-03-31 15:42:26
【问题描述】:

在下面的代码中,我希望以某种方式更改的注释部分应该能够设置文档的正文而不是“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”没有引用“正确的”。

【问题讨论】:

  • 文档的正文是客户端,您应该使用模板引擎并将要更改的变量发送到<body>所在的布局。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2020-12-16
    • 2015-11-25
    • 1970-01-01
    • 2017-06-03
    • 2013-04-04
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多