我有很多提供数据但需要时间的服务,因此有一种方法可以将控件保存在angularJS或JQuery中,一旦其他代码完成,该控件将被执行。

例如:

function fun1(){
  // many functions get data
}

function fun2(){
  // many functions get data
}

function fun3(){
 // here I want to call fun1()
 //once fun1() is executed then only call fun2()
}


任何想法如何在angularJS中实现这一目标?

提前致谢。

最佳答案

您可以使用Promise或$ q

有关更多详细信息,请参见此处https://docs.angularjs.org/api/ng/service/$q

function fun1(){
   var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);

  return deferred.promise;
}

function fun2(){
  // many functions get data
}

function fun3(){
  // here I want to call fun1()
  //once fun1() is executed then only call fun2()

  var promise = fun1();

  promise.then(function() {
    //called if fun1 return successfully
    fun2();
  }, function(reason) {
       alert('Failed: ' + reason);
  }, function(update) {
     alert('Got notification: ' + update);
  });
}

关于javascript - 如何在angularJS或JQuery或JavaScript中保存控件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29412233/

10-12 02:23