如何等待异步 JSZip .forEach() 调用在 运行 下一个代码之前完成?

How to wait for asynchronous JSZip .forEach() call to finish before running next code?

我有一个名为 'data' 的全局变量,它正在 forEach 循环中被修改。但是,由于循环是异步的,因此代码不会等到数据填充后再继续执行代码。这是使用 JSZip 库。

let data = [];

await zip.folder("folderName").forEach(async function (relativePath, file) {
            let json = await zip.file(file.name).async("text");
            data.push(json);
            console.log(data.length); // prints increasing numbers
        });

console.log(data.length); //prints 0
// need to do something with data but it is empty

如何在继续代码之前等待数据数组被填充?

根据 JSZip 文档,无法将 forEach(callback) 转换为 Promise 数组。所以我想到的唯一方法是获取文件数量并使用计数器。

const myFolder = zip.folder("folderName");
const numberOfCallbacks = Object.keys(myFolder.files).length - 1;
let counter = 0;
myFolder.forEach((relativePath, file) => {
    // your code. you'd better create a Promise here and add it to an array of promises.
    counter++;
    if (counter === numberOfCallbacks) {
        // everything is done. If you created Promise above, here you can use Promise.all()
    }
});

我测试了上面的代码并且它有效。如果有问题请告诉我。

forEach() has no return value so it cannot be awaited. You'll have to populate an array of promises from each ZipObject#async() and await that array using Promise.all()得到结果:

const promises = [];

zip.folder("folderName").forEach(function (relativePath, file) {
  promises.push(zip.file(file.name).async("text"));
});

Promise.all(promises).then(function (data) {
  // do something with data
});