嵌套的匿名函数不会运行(JavaScript)

发布于 2025-01-31 12:55:22 字数 453 浏览 4 评论 0原文

我正在尝试制作一个嵌套匿名函数的回调函数。我的代码看起来像这样:

    function submitGuess(guess) {
        if (guess.length === 5) {
            console.log("The guess was 5 letters");
            const postGuess = async () => {
                console.log("Anon function initiated")
                const res = await fetch(SOME_URL);
            }
        }
    }
    submitGuess(guess)

但是匿名函数从未启动。第二个console.log永远不会运行,我不知道为什么。

I am trying to make a callback function that has an anonymous function nested inside. My code looks something like this:

    function submitGuess(guess) {
        if (guess.length === 5) {
            console.log("The guess was 5 letters");
            const postGuess = async () => {
                console.log("Anon function initiated")
                const res = await fetch(SOME_URL);
            }
        }
    }
    submitGuess(guess)

But the anonymous function never initiates. The second console.log never runs, and I can't figure out why.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄人书 2025-02-07 12:55:22

新答案:感谢您的反馈

// declare the function
async function submitGuess(guess) {
    if (guess.length === 5) {
        console.log("The guess was 5 letters");
        const postGuess = async () => {
            console.log("Anon function initiated")
            const res = await fetch("url");
        };
        await postGuess(); // call the function
    }
}

submitGuess("input");

旧:
确保您声明功能,然后打电话给它们!

// declare the function
function submitGuess(guess) {
    if (guess.length === 5) {
        console.log("The guess was 5 letters");
        postGuess(); // call the function
    }
}

// declare the function
const postGuess = async () => {
    console.log("Anon function initiated")
    const res = await fetch(SOME_URL);
}

submitGuess(guess)

NEW ANSWER: THANKS FOR FEEDBACK

// declare the function
async function submitGuess(guess) {
    if (guess.length === 5) {
        console.log("The guess was 5 letters");
        const postGuess = async () => {
            console.log("Anon function initiated")
            const res = await fetch("url");
        };
        await postGuess(); // call the function
    }
}

submitGuess("input");

OLD:
Make sure you declare the functions then you call them !!

// declare the function
function submitGuess(guess) {
    if (guess.length === 5) {
        console.log("The guess was 5 letters");
        postGuess(); // call the function
    }
}

// declare the function
const postGuess = async () => {
    console.log("Anon function initiated")
    const res = await fetch(SOME_URL);
}

submitGuess(guess)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文