如标题所述,仅当某些条件完成后,如何才能运行其余代码(位于主函数下方)?例如:



function foo() {
   count = 0;
   var interval = setInterval(function() {
      count++;
      if (count == 10) {
         clearInterval(interval);
		 console.log('Done');
      }
   }, 1000);
}

foo();

console.log("It should display after Foo() is done");

最佳答案

您应该为此使用promise。然后您的代码将如下所示

  function foo() {
      return new Promise(function(resolve , reject){

       count = 0;
       var interval = setInterval(function() {
          count++;
          if (count == 10) {
             clearInterval(interval);
             console.log('Done');
              resolve();
          }
       }, 1000);
       })

    }

    foo().then(function(){

    console.log("It will be displayed after Foo() is done");
})

10-05 20:41
查看更多