解决异步函数“not a function”错误的方法在JavaScript异步编程中,当直接调用异步函数返回对象的方法时,常会遇到“not a function”错误。这源于对async function返回值机制的误解。
错误原因分析
- async函数始终返回Promise:即使函数体显式返回一个对象,调用该函数也会立即返回一个Promise对象,而非直接返回对象本身。
- 直接调用方法的后果:尝试通过getData().isCorrect()调用方法时,实际是在Promise对象上调用方法,而Promise本身没有该方法,导致错误。
正确处理方法
1. 使用.then()方法处理Promise通过.then()方法等待Promise解析,并访问解析后的对象:
getData().then(obj => obj.isCorrect())2. 完整示例代码HTML部分<button onclick="getData().then(obj => obj.isCorrect())">Submit</button>JavaScript部分async function getData() { const response = await fetch("https://all-wordle-words.kobyk1.repl.co/script.js"
); const data = await response.json(); const wordsArray = data; const words = new Set(wordsArray); const chosen = wordsArray[Math.floor(Math.random() * wordsArray.length)]; function check(word) { let result = Array(5).fill("gray"); let chosenChars = [...chosen]; for (let i = 0; i < 5; i++) { if (word[i] === chosenChars[i]) { result[i] = "green"; chosenChars[i] = "G"; } else { for (let j = 0; j < 5; j++) { if (word[i] === chosenChars[j]) { result[i] = "yellow"; chosenChars[j] = "Y"; } } } } return result; } function isCorrect() { let word = document.getElementById("guess").value.toLowerCase(); if (words.has(word)) { let result = check(word); let element = document.getElementById("guesses"); element.innerHTML += colorResult(word, result); if (chosen === word) { alert("You found the word!"); } } else { alert("Sorry, that word is not in our dictionary!"); } } function colorResult(word, result) { word = word.toUpperCase(); let columns = ""; for (let i = 0; i < 5; i++) { columns += `<td style="background-color: ${result[i]};">${word[i]}</td>`; } return "<tr>" + columns + "</tr>"; } return { check, isCorrect, colorResult };}注意事项
1. 错误处理使用.catch()方法捕获Promise链中的错误:
getData() .then(obj => obj.isCorrect()) .catch(error => { console.error("处理错误:", error); alert("发生错误,请稍后再试。"); });2. 异步操作粒度- 保持职责单一:若getData函数包含大量业务逻辑,建议拆分为更小的异步函数,每个函数负责单一职责。
3. async/await在事件处理中的应用在JavaScript代码中定义事件监听器时,可使用async/await提高可读性:
document.getElementById('submitButton').addEventListener('click', async () => { try { const dataFunctions = await getData(); dataFunctions.isCorrect(); } catch (error) { console.error("处理错误:", error); alert("发生错误,请稍后再试。"); }});- 不推荐在HTML中直接使用async/await:如onclick="async () => { ... }"的可读性和维护性较差,建议在JavaScript文件中管理事件监听器。
总结
通过正确处理Promise,可编写出更健壮、更符合预期的异步JavaScript代码。