【问题标题】:How do I make a synchronous call in a recursive method?如何在递归方法中进行同步调用?
【发布时间】:2019-10-18 01:07:15
【问题描述】:

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

我尝试使用承诺,但我只是不明白在 .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 只是一个例子,我只是想让异步调用同步。

【问题讨论】:

  • setTimeout 产生一个异步函数,而不是一个同步函数。
  • 感谢您的回复。我更新得更清楚了。我想让那个异步调用同步。
  • 好吧,你永远不会让异步函数同步。但您可能仍然可以交错调用。
  • 那就不要使用setTimeout,它本质上是异步的。
  • 但是没有办法使异步调用同步。世界不是这样运作的。

标签: javascript recursion promise async-await synchronous


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2016-03-02
    • 2017-06-08
    相关资源
    最近更新 更多