Javascript 如何在递归方法中进行同步调用?
我试图运行一个调用,并在完成另一个函数之前阻止递归函数继续运行 我试图使用promise,但我不明白在Javascript 如何在递归方法中进行同步调用?,javascript,recursion,promise,async-await,synchronous,Javascript,Recursion,Promise,Async Await,Synchronous,我试图运行一个调用,并在完成另一个函数之前阻止递归函数继续运行 我试图使用promise,但我不明白在.then()部分中放什么,因为这是一个递归调用 const htmlString = '<table><tr><td>Bah</td><td>Pooh</td></tr></table>'; const fragment = document.createRange().c
.then()
部分中放什么,因为这是一个递归调用
const htmlString = '<table><tr><td>Bah</td><td>Pooh</td></tr></table>';
const fragment =
document.createRange().createContextualFragment(htmlString);
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function asynchronousCallWantingtoMakeSynchronous() {
return new Promise((resolve, reject) => {
setTimeout(function() {
return resolve ( console.log("should come before another recursive call"))
}, 0)
});
}
walkTheDOM(fragment, function(node) {
console.log(node)
asynchronousCallWantingtoMakeSynchronous.then(function(){
})
})
consthtmlstring='BahPooh';
常量片段=
document.createRange().createContextualFragment(htmlString);
函数walkTheDOM(节点,func){
func(节点);
node=node.firstChild;
while(节点){
漫游域(节点,函数);
node=node.nextSibling;
}
}
函数asynchronouscallwanting to akesynchronous(){
返回新承诺((解决、拒绝)=>{
setTimeout(函数(){
返回resolve(console.log(“应该在另一个递归调用之前”))
}, 0)
});
}
漫游域(片段、函数(节点){
console.log(节点)
AsynchronousCallWantingToakesynchronous.then(function()){
})
})
实际打印出的内容:
<table>...</table>
<tr>...</tr>
<td>Bah</td>
"Bah"
<td>Pooh</td>
"Pooh"
"should come before Pooh"
。。。
...
呸
“呸”
维尼
“呸”
“应该在维尼之前”
我真正想要的是:
<table>...</table>
"should come before another recursive call"
<tr>...</tr>
"should come before another recursive call"
<td>Bah</td>
"should come before another recursive call"
"Bah"
"should come before another recursive call"
<td>Pooh</td>
"should come before another recursive call"
"Pooh"
"should come before another recursive call"
。。。
“应位于另一个递归调用之前”
...
“应位于另一个递归调用之前”
呸
“应位于另一个递归调用之前”
“呸”
“应位于另一个递归调用之前”
维尼
“应位于另一个递归调用之前”
“呸”
“应位于另一个递归调用之前”
请记住,setTimeout只是一个示例,我只想使异步调用同步 无法使异步函数同步。但是您可以使用
承诺
或异步等待
使其感觉更像这样。你可以用这些来分散你的通话
consthtmlstring='BahPooh';
const fragment=document.createRange().createContextualFragment(htmlString);
异步函数asyncWalkTheDOM(节点、函数、穿插){
func(节点);
node=node.firstChild;
while(节点){
等待散布(节点)
异步漫游域(节点、函数、穿插);
node=node.nextSibling;
}
}
异步函数asynchronousCall(节点){
返回新承诺(函数(res,rej){
setTimeout(函数(){
log(“应该在另一个递归调用之前出现”)
资源(节点)
}, 0)
})
}
asyncWalkTheDOM(片段、函数(节点){
console.log(node.nodeName)
},asynchronousCall)
setTimeout
生成的是异步函数,而不是同步函数。感谢您的回复。我更新了以更加清楚。我想让那个异步调用同步。你永远不会让一个异步函数同步。但是您可能仍然能够交错调用。然后不要使用setTimeout
,这本身就是异步的。但是没有办法使异步调用同步。世界不是这样的。