[英]How to wait for asynchronous JSZip .forEach() call to finish before running next code?
I have a global variable called 'data' that is being modified inside a forEach loop.我有一个名为“data”的全局变量,它正在 forEach 循环中进行修改。 However, since the loop is asynchronous, the code does not wait until data is populated before it continues with the code.但是,由于循环是异步的,因此代码不会等到填充数据后才继续执行代码。 This is using the JSZip library.这是使用 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
How do I wait for the data array to be populated before I continue with the code?在继续执行代码之前,如何等待填充数据数组?
forEach()
has no return value so it cannot be awaited. forEach()
没有返回值,因此不能等待。 You'll have to populate an array of promises from each ZipObject#async()
and await
that array using Promise.all()
to get the results:您必须从每个ZipObject#async()
填充一个 promise 数组,并使用Promise.all()
await
该数组以获取结果:
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
});
According to JSZip documentation, there's no way to convert forEach(callback)
to an array of Promise
s.根据 JSZip 文档,无法将forEach(callback)
转换为Promise
数组。 So the only way I came up with was to get the number of files and use a counter.所以我想出的唯一方法是获取文件数量并使用计数器。
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()
}
});
I tested the above code and it worked.我测试了上面的代码并且它起作用了。 Let me know if there's a problem.让我知道是否有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.