从具有promise的函数返回一个数组

时间:2017-11-21 22:41:56

标签: javascript angularjs promise angular-promise

我需要在填充数组后从此函数返回数组lotSpecItems

public getLotSpecItems(id: number) {
    let toReturn = this.resourceClass.getLotSpecItems({ lotId: id });
    let lotSpecItems = [];
    return toReturn.$promise.then(lotSpecItemsArray => {
        lotSpecItemsArray.forEach(lotSpecItem => {
            lotSpecItems.push(this.$di.logicFactory.getLotSpecLogic().mapLotSpecItem(lotSpecItem));
        });
    });
}

$promise是一个有角度的js承诺:(property) angular.resource.IResourceArray<any>.$promise: ng.IPromise<ng.resource.IResourceArray<any>>

客户端代码(可编辑为不期望承诺):

$onInit() {
    this.lotLogic.getLotSpecItems(this.lot.id).then((results) => {
        this.searchResults = results;
        console.log(this.searchResults);
    });

目前返回undefined。我做错了什么?

1 个答案:

答案 0 :(得分:3)

您没有从$promise.then()返回任何内容。返回新数组,以便在下一个then()

中使用
public getLotSpecItems(id: number) {
    let toReturn = this.resourceClass.getLotSpecItems({ lotId: id });
    let lotSpecItems = [];
    return toReturn.$promise.then(lotSpecItemsArray => {
        lotSpecItemsArray.forEach(lotSpecItem => {
            lotSpecItems.push(this.$di.logicFactory.getLotSpecLogic().mapLotSpecItem(lotSpecItem));
        });
        // Now return the array
        return lotSpecItems; 
    });
}