Javascript JS-对异步函数的递归调用会弄乱堆栈
我很难理解在JS中递归调用期间堆栈是如何工作的 我想制作一个机器人来解析维基百科文章,并为我提供这些文章的链接。 我正在使用WikimediaAPI,它允许获取我要查找的数据 我正在使用我自己的一个对象,称为Leaf,它允许我构建一棵树。其结构如下:Javascript JS-对异步函数的递归调用会弄乱堆栈,javascript,reactjs,recursion,d3.js,Javascript,Reactjs,Recursion,D3.js,我很难理解在JS中递归调用期间堆栈是如何工作的 我想制作一个机器人来解析维基百科文章,并为我提供这些文章的链接。 我正在使用WikimediaAPI,它允许获取我要查找的数据 我正在使用我自己的一个对象,称为Leaf,它允许我构建一棵树。其结构如下: Leaf = { "id":123, "name":foo, "depth":1, "children":[Leaf, Leaf, Leaf] } 我打算这样做:首先从随机页面获取数据,然后将其放入叶子对象中 randomPageFetch =
Leaf = {
"id":123,
"name":foo,
"depth":1,
"children":[Leaf, Leaf, Leaf]
}
我打算这样做:首先从随机页面获取数据,然后将其放入叶子对象中
randomPageFetch = async () => {
const responseJson = await fetch('https://fr.wikipedia.org/w/api.php?action=query&format=json&rnnamespace=0&list=random&rnlimit=1&origin=*').then(res => res.json())
let newLeaf = new Leaf (responseJson.query.random[0].id,responseJson.query.random[0].title, [], 1)
newLeaf = await this.fetchLinksFromPage(newLeaf)
return newLeaf
}
我做过一次,因为这是我唯一一次需要一个随机页面。完成后(如您所见),我调用第二个函数,解析本文中的链接
fetchLinksFromPage = async (leaf) =>{
var responseJson = await fetch('https://fr.wikipedia.org/w/api.php?action=query&format=json&gpllimit='+MAX_LINKS_PER_PAGE+'&titles='+leaf.name+'&generator=links&origin=*').then(res => res.json())
try{
await Object.entries(responseJson.query.pages).forEach(async(element) => {
if (element[1].ns === 0 && element[1].pageid > 0){
var newLeaf = await new Leaf(element[1].pageid, element[1].title, [], leaf.depth + 1)
if (newLeaf.depth < MAX_DEPTH) {
newLeaf.children = await this.fetchLinksFromPage(newLeaf)
}
leaf.children.push(newLeaf)
return leaf
}
})
}
catch(e){
console.log(e, "IN RESPONSE ", responseJson, "FROM ", leaf.name)
}
return leaf
}
然而,当我登录forEach循环时,它似乎做了类似的事情
fetch(depth = 1)
fetch(depth = 1)
fetch(depth = 1)
**RETURN TO FIRST FUNCTION**
fetch(depth = 2)
fetch(depth = 2)
fetch(depth = 2)
**RETURN TO FIRST FUNCTION**
fetch(depth = 3)
fetch(depth = 3)
fetch(depth = 3)
我不熟悉async/await,所以我不确定这种行为是否是有意的。您对如何解决此问题有何想法?async await在高阶函数中的行为与您想象的不一样,请检查此项:。用一个简单的for..of循环替换它,然后重试。另外,您不需要使用then catch,因为您在获取时已经在使用异步等待。
await[…]。forEach()
==await undefined
,因此无点感谢很多,我不知道for…of
循环,它解决了我的问题!
fetch(depth = 1)
fetch(depth = 1)
fetch(depth = 1)
**RETURN TO FIRST FUNCTION**
fetch(depth = 2)
fetch(depth = 2)
fetch(depth = 2)
**RETURN TO FIRST FUNCTION**
fetch(depth = 3)
fetch(depth = 3)
fetch(depth = 3)