Home  >  Q&A  >  body text

node.js - Promise改写的异步回调函数为何测试超时?

在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_leeringa_lee2721 days ago826

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 14:37:15

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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 14:37:15

    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.

    reply
    0
  • Cancelreply