繁体   English   中英

Async.each:所有执行后仅一个回调

[英]Async.each :only one callback after all executed

我有一个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

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

(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 这是一个例子 唯一的区别是您的callback将给定一个附加参数,该参数是所有success的数组。

我认为您应该尝试等待每个“每个”返回,然后如果您认为一切都很好,则请console.log。 在async.each内部,除非使用复杂的代码,否则您将无法知道每个“每个”都运行良好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM