BeniaminoBaggins
BeniaminoBaggins

Reputation: 12433

Return an array from a function with a promise

I need to return the array lotSpecItems from this function once it is populated:

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));
        });
    });
}

The $promise is an angular js promise: (property) angular.resource.IResourceArray<any>.$promise: ng.IPromise<ng.resource.IResourceArray<any>>

Client code (can be edited to not expect a promise):

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

It currently returns undefined. What am I doing wrong?

Upvotes: 1

Views: 951

Answers (1)

charlietfl
charlietfl

Reputation: 171669

You aren't returning anything from the $promise.then(). Return your new array so it is available in the next 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; 
    });
}

Upvotes: 3

Related Questions