【问题标题】:Adding async function to async waterfall向异步瀑布添加异步功能
【发布时间】:2019-01-02 07:09:51
【问题描述】:

我正在尝试开发一个 NodeJS 应用程序,但它不会按预期执行。我想先执行 downloadIMG 然后执行 featureMatching 并继续执行此操作,直到 for 循环终止。指导我以适当的方式重写代码。

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

【问题讨论】:

    标签: node.js asynchronous async-await


    【解决方案1】:

    here 得到答案。通过从异步函数返回 args 作为数组,可以在异步瀑布中使用异步函数。

    像这样

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

    【讨论】:

    • 有一种更简单、更优雅的方式。异步函数是 Promise。 Async.js 处理回调,而不是承诺。改用 async-q,它是为 Promise 设计的:npmjs.com/package/async-q
    • 避免仅链接答案,因为这些答案可能随时消失。相反,请在您的答案中添加链接源中的相关部分。
    • @k0pernikus 嘿,我在评论中提到了答案的相关部分!
    • 尝试使用新的 async/await... 如果你在 nodejs 上投入时间,最好学习这些,它们会让事情变得更容易。不再需要使用异步等库。
    猜你喜欢
    • 2015-07-18
    • 2018-11-13
    • 2020-09-06
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2014-10-09
    • 2016-01-20
    相关资源
    最近更新 更多