簡體   English   中英

Node.JS:為什么嵌套的Prom然后看起來會亂七八糟?

[英]Node.JS: Why do nested promise thens seem to run out of order?

我需要每個download和getFiles調用分別運行,因為firebase似乎無法處理太多連接。

const bucket = storage.bucket(bucketName); // firebase storage bucket
var queue = Promise.resolve();

websiteNames.reduce(function(promise, websiteName) {
    return promise
    .then(() => {
        mkdirp(websiteName)
    })
    .then(() => {
        console.log("now getting files: " + dirPath);
        return bucket.getFiles({prefix: dirPath})
    })
    .then(data => {
        console.log("got files");
        var files = data[0];
        files.forEach(function (file) {
            var storePath = tmpDir + "/" + file.name;
            queue = queue
            .then(() => {
                console.log("now downloading: " + file.name);
                return file.download({destination: storePath});
            })
            .then(() => {
                console.log(`downloaded to ${storePath}.`);
                return readFile(storePath, 'utf8');
            })
            .then(buffer => {
                console.log("readed file: " + storePath + " of buf size " + buffer.length);
            });
        });
    });
}, queue);

我希望大的then塊將把下載操作添加到已經具有所有getFiles操作的隊列中。 因此,我希望它在開始下載文件之前先進行所有getFiles調用。 但是控制台日志是這樣的:

now getting files: foo/a
got files
now downloading: foo/a/0.csv
now getting files: foo/b
got files
now getting files: foo/c
got files
downloaded to /tmp/foo/a/0.csv.

為什么在進行所有存儲桶getFiles調用之前foo / a / 0.csv開始下載? 在已經有getFiles之后,是否不應該將文件下載然后添加到隊列的末尾? 而且foo / a有多個文件,那么為什么在getFiles調用之間只偷偷下載了一個文件?

嵌套結構就是問題所在。 當所有外部的請求都不在隊列中時,沒有機制可以防止內部循環向隊列做出承諾。 一旦創建第一個Promise,它將開始“工作”,並且將調用處理程序,因此,如果您還沒有添加所有Promise,那么第一個Promise就會再次將Promises添加到隊列中,您將得到您所觀察到的。

嵌套的結構使之成為不可能。 看看Promise.all 首先使用所有文件下載Promises構建一個獨特的Array。 當Promise.all解決了所有承諾后,詢問Array,然后使用內部循環將then處理程序附加到Promise.all。

Promise.all將包含所有文件的數組,您可以通過構建另一個不同的隊列來執行更多步驟。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM