node.js - Promise改写的异步回调函数为何测试超时?
ringa_lee
ringa_lee 2017-04-17 14:35:15
0
2
872

在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出去
        })
    });
}
ringa_lee
ringa_lee

ringa_lee

reply all(2)
巴扎黑

koa I have never used it. I have always felt that this weird method of using generator 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 setting status is correct:

ctx.status = 200;

Secondly, you can try changing the test like this:

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();
            });
    });
})

Supplement:

I see that koa-router 7.x works with koa 2.x to support the async/await syntax. Are you sure you are using the correct version?

Check the official example supports promises for async/await

Lastly, I have never used this strange thing, please look for more documentation yourself

Added again:

Indeed, as @wusisu said, there is something wrong with your request writing and 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出去
            }
            resolve(body);
        })
    });
}
巴扎黑

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template