How can I let spellcheckePub() function know when gatherWords() function is fully done executing? gatherWords() is processing epub books so it takes a while and when I console.log(words) it is empty, presumably because the forEach hasn't completed yet.
masterePub is a zip(epub) loaded with jszip. forEach executes for each file/dir listing in loaded zip file.
function spellcheckePub() {
gatherWords();
console.log(words);
// do stuff with words
}
function gatherWords() {
words = [];
masterePub.forEach(function (relativePath, file) {
if (!file.dir) {
masterePub.file(file.name).async("text")
.then(function success(content) {
//make an array of words
content = content.split(/\s /);
words = words.concat(content);
});
}
});
} // end spellcheckePub function
CodePudding user response:
Collect the promises you create in an array, call Promise.all
on it:
async function spellcheckePub() {
const words = await gatherWords();
console.log(words);
// do stuff with words
}
async function gatherWords() {
const promises = [];
masterePub.forEach((relativePath, file) => {
if (!file.dir) {
promises.push(file.async("text").then(content => {
//make an array of words
return content.split(/\s /);
}));
}
});
const wordArrays = await Promise.all(promises);
return wordArrays.flat();
}