
在JavaScript中,当一个函数被声明为async时,它会隐式地返回一个Promise。无论你在async函数中显式地返回什么值,这个值都将被包裹在一个已解析(resolved)的Promise中。如果async函数中抛出错误,则会返回一个已拒绝(rejected)的Promise。
这意味着,当你调用一个async函数时,你立即得到的是一个Promise对象,而不是该函数最终计算出的结果。要获取Promise解析后的实际值,你需要使用.then()方法或者在另一个async函数中使用await关键字。
考虑以下JavaScript代码,它模拟了一个异步获取数据并返回一组校验函数的场景:
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) { /* ... */ }
function isCorrect() {
let word = document.getElementById("guess").value.toLowerCase();
if (words.has(word)) {
// ... 逻辑
} else {
alert("Sorry, that word is not in our dictionary!");
}
}
function colorResult(word, result) { /* ... */ }
return {
check,
isCorrect,
colorResult
}
}在上述getData函数中,它最终返回了一个包含check、isCorrect和colorResult方法的对象。然而,由于getData是一个async函数,当你调用getData()时,它并不会立即返回这个对象,而是返回一个Promise。
立即学习“Java免费学习笔记(深入)”;
如果在HTML中,你尝试通过onclick事件直接调用getData().isCorrect(),就会遇到“getData(...).isCorrect is not a function”的错误。
<button onclick="getData().isCorrect()">Submit</button>
这是因为getData()的返回值是一个Promise对象,而Promise对象本身并没有isCorrect这个方法。你试图在Promise对象上直接访问其最终解析值上的方法,这显然是不正确的。
要正确地访问async函数返回的Promise所解析的值,你需要等待Promise解析完成。在onclick事件这种需要立即执行回调的场景中,使用.then()方法是常见的解决方案。
.then()方法接受一个回调函数作为参数,当Promise成功解析时,这个回调函数会被执行,并且Promise解析后的值会作为参数传递给它。
将HTML中的按钮点击事件修改为以下形式:
<button onclick="getData().then(obj => obj.isCorrect())">Submit</button>
代码解析:
以下是修正后的HTML和JavaScript代码结构:
JavaScript (script.js)
async function getData() {
// 模拟API调用,实际应用中替换为真实API地址
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); // 修正:result 变量声明
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
}
}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>
注意事项:
错误处理: 在实际应用中,Promise操作应该总是包含错误处理。你可以通过在.then()之后链式调用.catch()来捕获Promise中的错误,例如:
getData()
.then(obj => obj.isCorrect())
.catch(error => console.error("An error occurred:", error));UI阻塞: 尽管async函数是非阻塞的,但如果isCorrect()内部有大量同步计算,仍然可能短暂阻塞UI。对于复杂的交互,考虑将UI更新和复杂计算分离,或使用Web Workers。
函数执行时机: getData()在每次点击按钮时都会被调用,这意味着它会每次都重新发起网络请求并处理数据。如果数据是静态的或不经常变化的,更好的做法是在页面加载时只调用getData()一次,并将返回的对象存储在一个全局变量或模块作用域中,以便后续点击事件直接使用。 例如:
let gameLogic = null; // 存储解析后的对象
async function initGame() {
gameLogic = await getData();
// 可以在这里做一些初始化UI的操作
}
// 页面加载时调用
document.addEventListener('DOMContentLoaded', initGame);
// 按钮点击事件
document.getElementById("submitButton").onclick = () => {
if (gameLogic) {
gameLogic.isCorrect();
} else {
console.warn("Game logic not yet loaded!");
}
};这种方式将数据加载和事件处理解耦,并避免了重复的网络请求。
理解JavaScript中async函数返回Promise的特性是处理异步操作的关键。当遇到“not a function”错误时,首先检查你是否在Promise对象上直接调用了其解析值上的方法。通过正确使用.then()(或在合适的上下文中使用await),你可以确保在Promise解析完成后再访问其内部属性或方法,从而编写出健壮、可靠的异步代码。
以上就是JavaScript异步函数返回值处理:解决'not a function'错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号