Friday, 21 April 2017

Using Nodejs to perform image manipulations async and cannot understand promises or callbacks to determine when all manipulations are done

I apologize for asking a question that has been posted many times already but I cannot understand how to adapt the examples/solutions/tutorials to my code. I am constrained by modifying someone else's code and cannot start from scratch.

I am using nodejs v6.10 and async code processing is difficult to implement for me despite reading many articles and wikis.

I am trying to determine exactly when all the operations are complete and I believe promises are the right way for me. I cannot figure out how to get it to work correctly, but I am not getting any warnings or errors anymore.

I think my biggest problem is that my image manipulation functions don't return anything and I'm trying to force them to without success.

here is my basic code:

var finished;
main();

function main() {
    do stuff...
    fs.readFile(JSON,...) { 
        finished = theApp(JSON);
});

Promise.all(finished).then(function(x, y) {
    var total = x * y;
    console.log("completed: " + total + " at " + Date.now());
        }).catch(function() {
            console.log("failed.");
        });
}

function theApp(JSON) {
    do stuff...
    for $loop (1..100) {
        do JSON stuff...
        resizeImages(JSONparameters, image);
    }

    for $loop2 (1..100) {
        do JSON stuff...
        finished = function() {
            return manipulateImages(JSONparameters, image);
        }
    }
}

function resizeImages(JSONparameters, image) {
    do stuff...
    for $i (1..100) {
        sharp(image)
            .resize(x, y)
            .toFile(output)
    }
}

function manipulateImages(JSONparameters, image) {
    return new Promise(function(resolve, reject) {
        do stuff...
        for $i (1..100) {
            sharp(image)
                .blur()
                .toFile(output)
        }
    });
}    

I realize it's a lot of loops, but this is the architecture that is my constraint for now. I also realize that I only put the promise at the manipulateImage step. This is because the resize operation completes before the manipulateImages operation starts.

In this configuration, the manipulateImages function is called many times, but nothing is output. If I strip out the "return new Promise" wrapper around the code, it works fine. But then I don't know how to return anything that can be passed back to main to wait until the promises.all() returns resolved.

Can someone please educate me on how to allow me to console.log the exact time when all the operations are complete? Thank you.



via noobuserpm

No comments:

Post a Comment