【问题标题】:Async.each :only one callback after all executedAsync.each : 全部执行后只有一个回调
【发布时间】:2017-12-23 05:41:23
【问题描述】:

我有一个async.each函数来按顺序执行以下操作。

1.从数组中获取图片大小。

2.裁剪图像。

3.上传到AWS s3。

现在我想在所有上传后显示一条成功消息。

async.each(crop_sizes,function (result,cb) {
    //crop image
    gm(path)
            .resize(result.width, result.height,'^')
            .crop(result.width, result.height)
            .stream(function (err,buffer) {
                //upload to s3
             s3.upload(params,function(err,success){
                   if(!errr){
                     conseole.log(uploaded);
                    }
                })
            });

  });

输出如下

uploaded
uploaded
uploaded
uploaded

但我想在所有上传后显示成功消息async 是否有可能

【问题讨论】:

  • 您的代码中有拼写错误。 errr 是什么,我在任何地方都没有看到它的定义。上传的是字符串还是变量?

标签: node.js express asynchronous async.js


【解决方案1】:

Async.each 采用第三次扩充,即:

A callback which is called when all iteratee functions have finished, 
or an error occurs. Invoked with (err).

您需要设置第三个参数以了解所有上传何时完成或某些上传是否失败。

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

【讨论】:

    【解决方案2】:

    (1) 当你在工作async.js 时,你应该总是在你的任务完成时触发回调,即cb。对于每项任务,它也应该是一次,不再是一次。如果您不触发它或在同一个任务中多次触发它,您的代码可能会挂起或您将分别收到错误。

    (2) async.each 有 3 个参数:colliterateecallback。您只使用 2。最后一个参数 callback 在所有任务完成时触发。

    async.each(crop_sizes, function task(result, cb) {
        //crop image
        gm(path)
            .resize(result.width, result.height, '^')
            .crop(result.width, result.height)
            .stream(function (err, buffer) {
                if (err)
                    return cb(err); // we use 'return' to stop execution of remaining code
                //upload to s3
                s3.upload(params, function(err,success){
                    if (err)
                        return cb(err);
                    cb(null, success);
                });
    
                // you could also simply do s3.upload(params, cb);
            });
    }, function allTasksAreDone (err) {
        if (err)
            console.log(err);
        // do something now
    });
    

    (3) 我认为如果你想得到每个任务的结果,你最好使用async.map。这是example。唯一的区别是你的callback 将有一个额外的参数,它是你所有的successes 的数组。

    【讨论】:

      【解决方案3】:

      如果您认为一切正常,我认为您应该尝试等待每个“每个”返回,然后是 console.log。在您的 async.each 中,除了使用复杂的代码之外,您将无法知道每个“每个”都运行良好

      【讨论】:

        猜你喜欢
        • 2015-07-20
        • 1970-01-01
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 2015-06-05
        • 2016-01-26
        • 2017-08-12
        • 1970-01-01
        相关资源
        最近更新 更多