如何从循环中调用最后一个承诺

时间:2016-03-08 06:59:37

标签: javascript jquery angularjs typescript promise

我是新的承诺,任何身体都可以帮助 这里的承诺是随机解决的,如何在完全循环执行时解决循环中的最后一个承诺 这里假设this.selectedValues有4个值,但有时它只更新3个,有时它更新所有值(4),这是承诺的问题

var promise;
private values: Object[] = [];
_.each(this.selectedValues, (selectedValue) => {
    promise = that.valueService.getValuesForName(selectedValue).then((pg) => {
        values.push({
            Id: pg.Id,
            Name: pg.Name,
            Description: pg.Description,
            Policies: pg.Policies
        });
    });
});

if (promise !== undefined) {
    promise.then(() => { // i want to call promise only once for last index
        var data: Object = {
            Id: that.id,
            Name: name,
            Description: description,
            Values: values
        };
        that.updateEdit(data, name);
    });

2 个答案:

答案 0 :(得分:0)

var promise = Promise.resolve();
private values: Object[] = [];
_.each(this.selectedValues, (selectedValue) => {
    promise = promise.then(function() {
        return that.valueService.getValuesForName(selectedValue);
    }).then((pg) => {
        values.push({
            Id: pg.Id,
            Name: pg.Name,
            Description: pg.Description,
            Policies: pg.Policies
        });
    });
});

if (promise !== undefined) {
    promise.then(() => { // i want to call promise only once for last index
        var data: Object = {
            Id: that.id,
            Name: name,
            Description: description,
            Values: values
        };
        that.updateEdit(data, name);
    });
}

答案 1 :(得分:0)

thanks a lot for replying finally $q solved my problem

 var promise,promises=[];
private values: Object[] = [];
_.each(this.selectedValues, (selectedValue) => {
    promise = that.valueService.getValuesForName(selectedValue).then((pg) => {
        values.push({
            Id: pg.Id,
            Name: pg.Name,
            Description: pg.Description,
            Policies: pg.Policies
        });
    });
      promises.push(promise);
});

 var combinedPromise = this.$q.all(promises);
if (combinedPromise !== undefined) {
    combinedPromise.then(() => { // i want to call promise only once for last index
        var data: Object = {
            Id: that.id,
            Name: name,
            Description: description,
            Values: values
        };
        that.updateEdit(data, name);
    });