【问题标题】:AngularJS: Access promise callback outside a async method [duplicate]AngularJS:在异步方法之外访问承诺回调[重复]
【发布时间】:2017-03-30 10:01:09
【问题描述】:
function graphreport(agentList) {

    var b;
    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
    });

    console.log(b);
}

第一个 console.log 将返回该值。第二个控制台日志将返回undefined。如何在方法之外获取变量?顺便说一句,我正在解决方法中的一个承诺。

【问题讨论】:

  • 请显示所有相关代码
  • 你不能在 then 的范围之外使用它。它是异步的。你的外部 console.log 可能在内部调用之前调用
  • agentList 中有什么?
  • agentList 是我进行 API 调用的服务名称。
  • 我需要使用范围外的变量来生成图形/图表。有什么替代方法吗?

标签: javascript angularjs


【解决方案1】:

您可以通过使用promises 或回调来实现此目的。但是你将无法像你试图在一个线性过程中那样做到这一点。了解异步 JavaScript 行为。这是example fiddle

承诺

function graphreport(agentList) {

    var b;
    var self = this;
    var deferred = $q.defer();
    var promise = deferred.promise;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
        deferred.resolve(data.data.users.length);
    });

    promise.then(function (b) {
        console.log(b);
    });
}

带回调函数

function graphreport(agentList) {

    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        myCallack(data.data.users.length);
    });

    function myCallack(b) {
      console.log(b);
    }
}

demo fiddle 中使用 co & yield。

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($timeout, $q) {

   co(function *() {
     var deferred = $q.defer();
     var promise = deferred.promise;

     function someAsync() {
        $timeout(function () {
              deferred.resolve('test');
        }, 250);
     }

     someAsync();
     var b = yield promise;
     console.log(b);
   });
});

【讨论】:

  • @punithgowda 它对你有用吗?你可能会标记正确的答案?
【解决方案2】:

由于您的 var b 仅在 Promise 解决后才得到解决,因此您必须异步检索它。其中一种方法是您可以使用callback,如下所示。因此,当 promise 被解决时,b 会与您的 callback 函数一起返回。

function graphreport(agentList, callback) {
    var b;
    var self = this;
    agentList.getAgentsList()
            .then(function (data) {
                self.agents = data.data.users;
                console.log(data.data.users.length);
                b = data.data.users.length;
                //return the callback method
                return callback(null, b);
            });
}

graphreport(list, function(err, b){
  if(!err){
   console.log(b);
   }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 2012-12-17
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多