I have a global variable called 'data' that is being modified inside a forEach loop. 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.
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. You'll have to populate an array of promises from each ZipObject#async()
and await
that array using Promise.all()
to get the results:
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
});