Angular中$http异步请求, 当请求结束使用返回值的办法~

作者: Nishizhen 分类: Web技术 发布时间: 2015-02-10 08:21 ė 6没有评论

from:https://docs.angularjs.org/api/ng/service/$q

使用$q解决异步问题。

// for the purpose of this example let's assume that variables `$q` and `okToGreet`
// are available in the current lexical scope (they could have been injected or passed in).

function asyncGreet(name) {
  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;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

本文出自 逆时针's Place,转载时请注明出处及相应链接。

本文永久链接: http://www.nishizhen.cn/angular%e4%b8%adhttp%e5%bc%82%e6%ad%a5%e8%af%b7%e6%b1%82-%e5%bd%93%e8%af%b7%e6%b1%82%e7%bb%93%e6%9d%9f%e4%bd%bf%e7%94%a8%e8%bf%94%e5%9b%9e%e5%80%bc%e7%9a%84%e5%8a%9e%e6%b3%95/

0

发表评论

电子邮件地址不会被公开。 必填项已用*标注

验证码 * Time limit is exhausted. Please reload CAPTCHA.

Ɣ回顶部