如何将从$ promise返回的数据分配给全局变量

Sim*_*ion 5 javascript promise angularjs

我有两个服务,service1 and service2和我想调用的方法service1进入service2.

理想情况下,我想将返回的数据分配给service1.getMethod()声明为的全局变量var result = [].

这是代码:

服务1

.factory('service1', function (dependencies...) {
    var getMethod1 = function () {
       ...//making http get call
       return deferred.promise();
    };

    return {
       getMethod1 : getMethod1
    };
});
Run Code Online (Sandbox Code Playgroud)

服务2

.factory('service2', function (dependencies...) {
    var result = [];

    var getMethod2 = function () {
        Service1.getMethod1().then(function (data) {
            result = data;
    });

    //RUN METHOD
    getMethod2();

    //Here ideally, I would like result to contain `[object, object, object]`
    console.log(result); //instead it prints `undefined`
});
Run Code Online (Sandbox Code Playgroud)

所以,理想情况下,我想用什么将是resultservice2's其他的functions i.e. result[0].name,如果我在做什么是正确的做法等不确定.

请提供一个plunker demo or code snippet例子,如果不确定,请在下面写下评论.

谢谢!

dfs*_*fsq 5

您不能像尝试一样使用异步代码.result当您尝试使用变量时,该变量尚未填充.相反,你也应该做出getMethod2回报承诺,并使用它的then方法:

.factory('service2', function (dependencies...) {

    var getMethod2 = function () {
        return Service1.getMethod1();
    };

    // RUN METHOD
    getMethod2().then(function(result) {
        console.log(result);
    });
});
Run Code Online (Sandbox Code Playgroud)

您还可以缓存返回的数据:

.factory('service2', function (dependencies...) {

    var result;

    var getMethod2 = function () {
        return result ? $q.when(result) : Service1.getMethod1().then(function(data) {
            result = data;
            return result;
        });
    };

    // RUN METHOD
    getMethod2().then(function(result) {
        console.log(result);
    });
});
Run Code Online (Sandbox Code Playgroud)