Why did the asynchronous callback function rewritten by Promise time out?

  node.js, question

Other modules were used in koa2, which was asynchronous and wrapped with promise. as a result, there was a problem.

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);  //Do not print
 ctx.status = 200;
 })
 
 app
 .use(router.routes())
 .use(router.allowedMethods());
 
 //The test error timed out
 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);
 bracket
 resolve(body);  //did not resolve to go out
 })
 });
 bracket

koaI have never used it. I have always felt this strange use.generatorThe method of middleware is too “fascinating” to use. (Maybe I am too low)

First of all, (because do not understandkoa), the following settings are not clearstatusIs the method of is correct:

ctx.status = 200;

Secondly, the test can be changed as follows:

describe("test", function () {
 this.timeout(10000);
 it("send", function (done) {
 client
 .get('/send')
 .expect(200)
 .end(function(err, res) {
 if (err) return done(err);
 done();
 });
 });
 })

Add:

图片描述

I seekoa-router 7.xcoordinatekoa 2.xTo supportasync/awaitGrammar, are you sure the versions are correct?

Take a look at official examples.supports promises for async/await

Finally, I really haven’t used this strange thing. Please look for more documents yourself.

Again:

Indeed, such as@wusisuSay, yoursrequestThere is something wrong with the writing. It should be changed:

function Prequest(params) {
 return new Promise(function (resolve, reject) {
 request(params, function (error, response, body){
 if (error || !  body || body.code !  = 1) {
 return reject(error);  //return must go out here
 bracket
 resolve(body);
 })
 });
 bracket