
在JavaScript异步编程中,async function是处理异步操作的核心。然而,一个常见的误解是,当一个async function显式地返回一个值(例如一个对象)时,调用该函数会直接得到这个值。实际上,async function的返回值始终是一个Promise对象。这意味着,即使函数体内部返回了一个普通对象,函数调用本身也会立即返回一个Promise,而这个Promise在操作完成后才会解析(resolve)为那个普通对象。
考虑以下异步函数示例:
async function getData() {
// 模拟异步操作,例如网络请求
const response = await fetch("https://all-wordle-words.kobyk1.repl.co/script.js");
const data = await response.json();
// 假设 data 是一个数组
const wordsArray = data;
const words = new Set(wordsArray);
const chosen = wordsArray[Math.floor(Math.random() * wordsArray.length)];
function check(word) { /* ... */ }
function isCorrect() { /* ... */ }
function colorResult(word, result) { /* ... */ }
// 显式返回一个包含多个方法的对象
return {
check,
isCorrect,
colorResult
};
}当我们调用getData()时,它并不会立即返回{ check, isCorrect, colorResult }这个对象。相反,它会返回一个Promise。这个Promise在fetch和response.json()这些异步操作都完成,并且getData函数内部的return语句被执行后,才会解析为那个包含check、isCorrect和colorResult方法的对象。
因此,如果尝试直接通过getData().isCorrect()来调用isCorrect方法,实际上是在一个Promise对象上调用isCorrect,而不是在Promise解析后的目标对象上调用。由于Promise对象本身没有isCorrect这个方法,JavaScript运行时便会抛出“getData(...).isCorrect is not a function”的错误。
要正确访问异步函数返回的Promise所解析的值,我们需要使用Promise的.then()方法。.then()方法接受一个回调函数作为参数,当Promise成功解析时,这个回调函数会被执行,并且Promise解析后的值会作为参数传递给它。
<button onclick="getData().isCorrect()">Submit</button>
修改为:
<button onclick="getData().then(obj => obj.isCorrect())">Submit</button>
这段代码的含义是:
以下是经过修正的HTML和JavaScript代码片段:
HTML (index.html):
<h1>KORDLE</h1> <table id="guesses"> <tr></tr> </table> <br> <input type="text" id="guess"> <!-- 修正后的按钮点击事件 --> <button onclick="getData().then(obj => obj.isCorrect())">Submit</button>
JavaScript (script.js 或嵌入在HTML中):
async function getData() {
var response = await fetch("https://all-wordle-words.kobyk1.repl.co/script.js");
var 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)) {
// 确保 result 被正确定义
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
}
}注意事项:
getData()
.then(obj => obj.isCorrect())
.catch(error => {
console.error("处理错误:", error);
alert("发生错误,请稍后再试。");
});// 假设按钮有一个ID 'submitButton'
document.getElementById('submitButton').addEventListener('click', async () => {
try {
const dataFunctions = await getData();
dataFunctions.isCorrect();
} catch (error) {
console.error("处理错误:", error);
alert("发生错误,请稍后再试。");
}
});请注意,在HTML中直接写onclick="async () => { ... }"通常不被推荐,因为其可读性和维护性不如在JavaScript文件中管理事件监听器。
“not a function”错误在异步编程中是一个常见的陷阱,尤其是在不完全理解async function返回值机制时。核心要点在于:async function总是返回一个Promise。要访问Promise解析后的实际值或其上的方法,必须使用.then()方法等待Promise完成解析。通过正确地处理Promise,我们可以编写出更健壮、更符合预期的异步JavaScript代码。
以上就是异步函数返回值处理:解决“not a function”错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号