如何仅从循环中调用最后的承诺

how to call only last promise from loop

本文关键字:调用 最后的承诺 循环 何仅      更新时间:2023-09-26

我是新承诺,任何人都可以帮忙吗这里promise是随机解析的,全循环执行
时如何从循环中解析最后一个promise。这里假设这个.selectedValues 有 4 个值,但有时它只更新三个,有时它更新所有值(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);
    });
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);
    });
}
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);
    });