简体   繁体   English

尝试使用顺序承诺循环的问题(q)

[英]Problems trying to use for loops with sequential promises (q)

I am trying to call a series of promises sequentially using a for loop, but I am having trouble getting to work in the right order. 我试图使用for循环顺序调用一系列promises,但是我无法按正确的顺序工作。 Theoretically speaking, the console should log the first block but it instead logging the second (implying that the promises are all called at the same time as compared to the second promise only being called after the first). 从理论上讲,控制台应该记录第一个块,但是它会记录第二个块(意味着Promise全部被同时调用,而第二个promise仅在第一个之后被调用)。

I thought this might be similar to this link, but I think I'm declaring the function rather than calling it in the then declaration? 我认为这可能与此链接类似,但我认为我在声明函数而不是在当时的声明中调用它? How to sequentially run promises with Q in Javascript? 如何在Javascript中用Q顺序运行promises?

Expected output: 预期产量:

starting: 3 
ending: 3
starting: 2 
ending: 2
starting: 1  
ending: 1 

Actual output: 实际产量:

starting: 3 
starting: 2 
starting: 1 
ending: 1 
ending: 2 
ending: 3 

http://jsfiddle.net/4k6t9/3/ http://jsfiddle.net/4k6t9/3/

var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope, $q, $timeout) { 
   var temp = $q.when({});
   var arr = [3, 2, 1];

    arr.forEach(function(element) {
        temp = temp.then(delay(element));
    })

    function delay(timing) {
        var deferred = $q.defer();
        console.log('starting: ' + timing)
        $timeout(function() {
            console.log('ending: ' + timing);
            deferred.resolve(timing);
        }, timing * 1000);
        return deferred.promise;
    }
});

Your fiddle is slightly different from the code in the question. 你的小提琴与问题中的代码略有不同。 But you where nearly there. 但你几乎就在那里。 There was only missing one return statement. 只有一个返回声明丢失了。

You are right: temp = temp.then(delay(element)); 你是对的: temp = temp.then(delay(element)); calls delay . 呼叫delay What you want instead is returning a function which will call delay . 你想要的是返回一个会调用delay的函数。 (You had that in the fiddle.) (你有小提琴。)

The only thing missing there was a return to return it :) 缺少有唯一的办法就是一个return返回吧:)

Here is the working fiddle: http://jsfiddle.net/4k6t9/6/ 这是工作小提琴: http//jsfiddle.net/4k6t9/6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM