Sunday 21 May 2017

KOA / node.js outer function responds before callback finishes

First, I'm sorry for the title, I couldn't mind up something better. I thought I understand Node.js / KOA, at least the basics but now I'm starting to feel that I'm missing some fundamentals.

Take a look at the following code:

    router.put("/", 
    parse, 
    async function (ctx, next) {

        // do something

        await next();
    },
    async function (ctx, next) {

        // do something

        await next();
    },
    async function (ctx, next) {

        if (some condition) {

            gm(imageBuffer)
                .quality(80)
                .write(profile_path, async function (err) {
                    gm(imageBuffer)
                        .resize(60, 60)
                        .quality(80)
                        .write(chat_path,async function (err) {

                            await next(); // HERE 1

                        });
                });

        } else {
            await next();
        }

        // HERE 2
    },
    async function (ctx, next) {

        responses.success(ctx, "Success");
    }
);

So what this is all about. The ones that are familiar with KOA framework will immediately see what is going on here. Where my problem starts/ends is in the third async function. So what I'm trying to do here is some image manipulation (saving). gm is asynchronus, but as you can see from the code I'm using anonymous callback functions, and what I'm trying to achieve is that the last async function is being called when gm finishes through await next(); // HERE 1.

But what really happens is (from my understanding)... gm starts asynchronously.. and // HERE 2 is hit, and because there's nothing, end of function, KOA returns default 404 response. I simply can't understand why this is so and how to overcome this. What I really want to happen is when callback finishes await next(); // HERE 1 gets called and I can return success response. await next(); // HERE 1 of course gets called (eventually) but too late, because KOA already responds with 404.

If there is someone that is able and willing to explain what exactly is happening here, thank you.



via repca

No comments:

Post a Comment