[英]How do I make a synchronous call in a recursive method?
我正在尝试运行一个呼叫并停止递归 function 在完成另一个 function 之前继续运行。
我尝试使用 promise 但我只是不明白在.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(){
})
})
这实际上打印出什么:
<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 只是一个示例,我只是想让异步调用同步。
没有办法使异步 function 同步。 但是您可以使用Promises
或async-await
让它感觉更像这样。 你可以使用这些来打断你的电话
const htmlString = '<table><tr><td>Bah</td><td>Pooh</td></tr></table>'; const fragment = document.createRange().createContextualFragment(htmlString); async function asyncWalkTheDOM(node, func, intersperse) { func(node); node = node.firstChild; while (node) { await intersperse(node) asyncWalkTheDOM(node, func, intersperse); node = node.nextSibling; } } async function asynchronousCall(node) { return new Promise(function (res, rej) { setTimeout(function() { console.log("should come before another recursive call") res(node) }, 0) }) } asyncWalkTheDOM(fragment, function(node) { console.log(node.nodeName) }, asynchronousCall)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.