javascript - 如何在递归方法中进行同步调用?

标签 javascript recursion promise async-await synchronous

我正在尝试运行一个调用并在完成另一个函数之前停止递归函数继续运行。

我尝试使用 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 只是一个示例,我只是想让异步调用同步。

最佳答案

没有办法使异步函数同步。但是您可以使用 Promisesasync-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)

关于javascript - 如何在递归方法中进行同步调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436611/

相关文章:

node.js - 如何在 Node.js 中的异步函数上正确使用 Promise?

java - 为什么我的 firestore 函数向我的应用程序返回 null?

javascript - 当多个 'fail' 处理程序链接到延迟时,为什么会调用多个 'then' 处理程序?

javascript - Facebook 重定向查询

javascript - HTML Javascript - 用搜索字段替换按钮 onclick

javascript - 按 id 对 JavaScript 对象进行分组

javascript - 如何在 TypeScript 中将 API 请求的响应转换为带有 `class-transformer` 的类实例?

arrays - 递归函数不会中断

java - 为什么递归调用打印 '123456' 而不是 '1' ?

java - 典型 1 对 n 关系的 Stackoverflow 异常(递归)