我有一个名为'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
在继续执行代码之前,我该如何等待数据数组被填充?
forEach
看起来不是异步的,因此向其发送 promise 不起作用,它期望一个回调函数。 - Keithmap()
,但在这里不是一个选项,或者手动使用for
循环迭代集合,但在没有对API内部进行假设的情况下也不可能实现。 - Patrick Roberts