Nodejs发送瀑布请求

问题描述 投票:0回答:2

我有文件夹名称的动态数组和使用zip文件夹创建一个zip我面临的问题是因为库是异步的,即

zipFolder(source,dest,callback)

因为它是一个异步调用需要时间,我想阻止下一个请求,除非第一个请求是真的,

function (req, res)
     var folder = ['N','PP','Y'];//dynamic just an example

        for( var i = 0 ; i < folder.length ; i++) {
            var source = path.join(basePath,'/download/'+folder[i]);
            var dest =   path.join(basePath,'/createZip/'+folder[i]+'.zip');
            console.log('sending',folders[i])


            //this is async
            zipFolder(source,dest, function(err) {
                if(err) {
                    console.log('oh no!', err);
                } else {
                    console.log('EXCELLENT');//want to send the second,third,fourth if success
                }
            });
        }

总结:输出应该是这样的:

如果成功/响应,则发送文件1如果成功/响应则发送文件2

想要像瀑布一样等待回调响应来发送第二个文件

另外我想要一个方法来知道完成回调,这样我就可以发回回应

node.js async-await async.js waterfall
2个回答
0
投票

你可以使用每个像:

var each = require('async-each-series')
      var folder = ['N','PP','Y'];


       each(folder, function(items,callback){
        //insert each items to db in async way
           var source = path.join(basePath,'/download/'+items);
           var dest =   path.join(basePath,'/createZip/'+items+'.zip');
           zipFolder(source,dest, function(err) {
                    if(err) {
                        console.log('oh no!', err);
                    } else {
                        console.log(items,'inserted')
                        callback()
                    }
                });

    },function(err){
           if(err) console.log('error occured')
        console.log('all items uploaded');
    });

0
投票

尝试使用异步waterfall方法

https://caolan.github.io/async/docs.html#waterfall

运行函数的tasks数组,每个函数将结果传递给数组中的下一个。但是,如果任何任务将错误传递给自己的回调,则不执行下一个函数,并立即调用主回调并显示错误

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});

UPDATE

在你的用例中eachSeries更适用。

 var folder = ['N','PP','Y'];


      async.eachSeries(folder, function(item,callback){
            var source = path.join(basePath,'/download/'+item);
            var dest =   path.join(basePath,'/createZip/'+item+'.zip');

            zipFolder(source,dest, function(err) {
                if(err) {
                    console.log('oh no!', err);
                    callback();
                } else {
                    console.log('EXCELLENT');//want to send the second,third,fourth if success
                    callback();
                }
            });

     },function(){
         console.log('all items uploaded');
    });    .
© www.soinside.com 2019 - 2024. All rights reserved.