如何将Async / await与mutationObserver / arrive.js一起使用?

时间:2020-02-07 23:56:03

标签: javascript async-await

我正在使用arrival.js库来侦听进入DOM的新元素。它使用Mutation Observers监视DOM元素的创建。

我想在函数中使用async / await,使其在继续之前等待到达。js。

这是我的代码。

let run = async() => {
  
  console.log("begin run()");
  
  await setAndListen();
  
  console.log("end run() <-- this should be the last console.log()");
  
}


let setAndListen = async() => {

  console.log("beginning setAndListen()");
  
  document.arrive(".new", function() {
    
    console.log("new element arrived");
    
    // Using a setTimeout to *simulate* a delay.
    // In the real world, this code would naturally be delayed
    // because the element would take a few seconds to arrive 
    // in the DOM (an http request happens).
    // I'd like for the run() function should finish after 
    // this 2 second delay.
    setTimeout(function(){ 
      
      console.log("returning after 2 second delay");
      return
      
    }, 2000);


  });

  // Creating an element and adding it to the page.
  let newElement = document.createElement("div");
  newElement.classList.add("new");
  document.body.appendChild(newElement);
  
  console.log("end setAndListen()");

}

run();
<script src="https://cdnjs.cloudflare.com/ajax/libs/arrive/2.4.1/arrive.min.js"></script>

这是我在JS Bin上的测试代码的链接。它在开始时包括了come.js库,后跟我上面概述的代码。

https://jsbin.com/nanisox/edit?js,console,output

1 个答案:

答案 0 :(得分:1)

使您的=SUM(INDEX(COUNTIFS(WEEKNUM(A:A), 10, YEAR(A:A), 2020))) 立即返回setAndListen。然后在Promise回调中使用setTimeout来实现承诺。对于在嵌套回调内部返回值,Promise非常有用。

请查看以下示例。

resolve