在koa2使用了其他模块,是异步的方法,把他用promise包装了一下,结果出了问题
import Koa from "koa";
import Router from "koa-router";
import request from "request";
import supertest from "supertest";
const app = new Koa();
const router = new Router();
const client = supertest.agent(app.listen(3000));
router
.get("/send", async (ctx, next)=> {
let params = {...}
let aa = await Prequest(params);
console.log(aa);//不打印
ctx.status = 200;
})
app
.use(router.routes())
.use(router.allowedMethods());
//测试错误 超时了
describe("test", function () {
this.timeout(10000);
it("send", function (done) {
client
.get('/send')
.expect(200,done)
});
})
function Prequest(params) {
return new Promise(function (resolve, reject) {
request(params, function (error, response, body){
if (error || !body || body.code != 1) {
reject(error);
}
resolve(body);//并没有resolve出去
})
});
}
koa
I have never used it. I have always felt that this weird method of usinggenerator
to make middleware is too "attractive" and I really don't dare to use it. (Maybe I’m too low)First of all, (because I don’t understand
koa
), I don’t know whether the following method of settingstatus
is correct:Secondly, you can try changing the test like this:
Supplement:
I see that
koa-router 7.x
works withkoa 2.x
to support theasync/await
syntax. Are you sure you are using the correct version?Check the official example supports promises for async/await
Added again:
Indeed, as @wusisu said, there is something wrong with your
request
writing and should be changed:I am a veteran driver of koa@2.
But the problem is not with koa, but with the Promise not being returned.
I also don’t understand the use of the request function. I suggest you print it in the callback of request.