加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在AngularJS中使用q的多链延迟函数停止返回数据

发布时间:2020-12-17 08:40:45 所属栏目:安全 来源:网络整理
导读:我试图链接在一起多个延迟函数调用,使下一个调用获得以前的deferred.resolve的结果。当我连接在一起超过2个这些调用,数据停止返回。 这里是角度控制器中的基本代码: $scope.runAsync = function() { var asyncFn1 = function(data){ var deferred = $q.de
我试图链接在一起多个延迟函数调用,使下一个调用获得以前的deferred.resolve的结果。当我连接在一起超过2个这些调用,数据停止返回。

这里是角度控制器中的基本代码:

$scope.runAsync = function() {
        var asyncFn1 = function(data){
            var deferred = $q.defer();

            $timeout(function(){
                console.log("Async fn1 " + data);
                $scope.outputLines.push("Async fn1 " + data);
                deferred.resolve("Async fn1 " + data);
            },1000);

            return deferred.promise;
        }

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

            $timeout(function(){
                console.log("Async fn2 " + data);
                $scope.outputLines.push("Async fn2 " + data);
                deferred.resolve("Async fn2 " + data);
            },1000);

            return deferred.promise;
        }

        asyncFn1(1)
        .then(function(data){asyncFn2(data)})
        .then(function(data){asyncFn2(data)})
        .then(function(data){asyncFn2(data)});
    }

当我运行这个我得到以下输出:

Async fn1 1
Async fn2 Async fn1 1
Async fn2 undefined
Async fn2 undefined

我如何将它们链接在一起,使第三个调用获得第二个调用的结果,第四个调用获得第三个调用的结果?

我创建了一个jsFiddle:http://jsfiddle.net/rhDyL/

摘自官方文档关于$ q:

then(successCallback,errorCallback) – regardless of when the promise
was or will be resolved or rejected calls one of the success or error
callbacks asynchronously as soon as the result is available. The
callbacks are called with a single argument the result or rejection
reason.

This method returns a new promise which is resolved or rejected via
the return value of the successCallback or errorCallback.

对于successCallack或errorCallback的返回值,根据Domenic’s slides:

if the return value is a promise then the promise adopts the returned
promise’s state otherwise the success callback is immediately called
with the return value

根据定义,您的代码缺少return关键字。应该如下:

asyncFn1(1)
    .then(function(data){return asyncFn2(data)})
    .then(function(data){return asyncFn2(data)})
    .then(function(data){return asyncFn2(data)});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读