简体   繁体   English

Javascript - 无法在 foreach 循环内调用 function

[英]Javascript - Unable to call function inside a foreach loop

I think I'm fundamentally misunderstanding something here in Javascript.我想我从根本上误解了 Javascript 中的一些东西。

Could someone please explain why I get SyntaxError: Unexpected identifier when trying to call getUrlContent from inside the forEach:有人可以解释为什么我在尝试从 forEach 内部调用getUrlContent时得到SyntaxError: Unexpected identifier

(async () => {

    let sitesState = []
    urlsToCheck.forEach(url => {
        sitesState.push({
            "url": url,
            "data": await getUrlContent(url)
        })
    })

})();

async function getUrlContent(url) { ... }

Why does this happen (and of course, how do I write this correctly?).为什么会发生这种情况(当然,我该如何正确地写这个?)。

Any help appreciated.任何帮助表示赞赏。

Thanks.谢谢。

You've used async in the wrong function.您在错误的 function 中使用了async Check this.检查这个。

    ( () => {

    let sitesState = []
    urlsToCheck.forEach(async(url) => {
        sitesState.push({
            "url": url,
            "data": await getUrlContent(url)
        })
    })

})();

async function getUrlContent(url) { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM