如何讓 spellcheckePub() 函式知道 collectWords() 函式何時完全執行?collectWords() 正在處理 epub 書籍,所以它需要一段時間,當我 console.log(words) 它是空的,大概是因為 forEach 還沒有完成。
masterePub 是一個加載了jszip的 zip(epub) 。forEach 為加載的 zip 檔案中的每個檔案/目錄串列執行。
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
uj5u.com熱心網友回復:
收集你在陣列中創建的 Promise,呼叫Promise.all它:
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();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493913.html
標籤:javascript 异步
上一篇:將方法轉換為異步
下一篇:導航控制器中的回圈導航
