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