
理解异步函数与Promise
在JavaScript中,当一个函数被声明为async时,它会隐式地返回一个Promise。无论你在async函数中显式地返回什么值,这个值都将被包裹在一个已解析(resolved)的Promise中。如果async函数中抛出错误,则会返回一个已拒绝(rejected)的Promise。
这意味着,当你调用一个async函数时,你立即得到的是一个Promise对象,而不是该函数最终计算出的结果。要获取Promise解析后的实际值,你需要使用.then()方法或者在另一个async函数中使用await关键字。
问题根源:直接访问Promise属性
考虑以下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”的错误。
这是因为getData()的返回值是一个Promise对象,而Promise对象本身并没有isCorrect这个方法。你试图在Promise对象上直接访问其最终解析值上的方法,这显然是不正确的。
解决方案:使用.then()处理Promise
要正确地访问async函数返回的Promise所解析的值,你需要等待Promise解析完成。在onclick事件这种需要立即执行回调的场景中,使用.then()方法是常见的解决方案。
.then()方法接受一个回调函数作为参数,当Promise成功解析时,这个回调函数会被执行,并且Promise解析后的值会作为参数传递给它。
将HTML中的按钮点击事件修改为以下形式:
代码解析:
- getData(): 这会立即调用async函数并返回一个Promise。
- .then(obj => obj.isCorrect()):
- .then()方法被链式调用在getData()返回的Promise上。
- 当getData()返回的Promise成功解析时(即数据获取和对象构建完成后),Promise解析后的值(也就是{ check, isCorrect, colorResult }这个对象)会被作为参数obj传递给箭头函数 obj => obj.isCorrect()。
- 此时,obj就是我们期望的包含isCorrect方法的对象,因此obj.isCorrect()能够被正确调用。
完整示例与注意事项
以下是修正后的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 += `${word[i]} `;
}
return "" + columns + " ";
}
return {
check,
isCorrect,
colorResult
}
}HTML (index.html)
KORDLE
注意事项:
-
错误处理: 在实际应用中,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解析完成后再访问其内部属性或方法,从而编写出健壮、可靠的异步代码。










