7

I'm trying to develop a NodeJS app, but it wont executing as desired. I want to first execute downloadIMG first and then execute featureMatching and continue this until the for loop terminates. Guide me to rewrite the code in proper manner.

for (var i=0; i<dbImgCount; i++) {
    (function(i) {
        async.waterfall([
            async function downloadIMG(done) {
                try {
                    var options = {
                        url:  FolderPath[i].FolderPath,
                        dest: '/home/ubuntu/imgCompare/'                
                    }
                    const { filename, image } =  await download.image(options);
                    image2 = 'image.jpg';
                    done(null, 'hi');
                } catch (e) {
                    console.error(e)
                }
            },
            async function featureMatching(a, done){
                const img1 = cv.imread(image1);
                const img = 'image.jpg';
                const img2 = cv.imread(img);
                const orbMatchesImg = matchFeatures({
                    img1,
                    img2,
                    detector: new cv.ORBDetector(),
                    matchFunc: cv.matchBruteForceHamming
                    },
                    (console.log(image1+','+img))
                );
                done(null);
            }
        ],
        function (err) {});
    })(i);
}

1 Answer 1

8

Got the answer from here. Async functions can be used in async waterfall by returning args as array from async function.

Like this

  async.waterfall([
           // ...
         async function (arg1, arg2) {
          //...
             const arg3 = await foo()

             return [arg1, arg2, arg3] //USE THIS, OTHERWISE 2ND fn WON'T WORK
         },
         function ([arg1, arg2, arg3], callback) {
           //...
         }
  ],function (err) {});
Sign up to request clarification or add additional context in comments.

4 Comments

There's a simpler, more elegant way. Async functions are promises. Async.js deal with callbacks, not promises. Use async-q instead which is designed for promises: npmjs.com/package/async-q
Avoid link only anwers as those can go away at any time. Rather, add the relevant part from the linked source within your answer.
@k0pernikus Hey, I mentioned relevant part of the answer in my comment!
Try to use the new async/await... If you are investing your time in nodejs, better learn those, they will make things much easier. No need to use libraries such as async anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.