簡體   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