【问题标题】:Return an array from a function with a promise从一个带有承诺的函数返回一个数组
【发布时间】:2017-11-22 06:51:43
【问题描述】:

填充后,我需要从该函数中返回数组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 是一个 Angular 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。我做错了什么?

【问题讨论】:

  • 我不明白为什么这样的问题会导致投票失败。此问题提供了识别问题、描述实际行为并解释所需行为的最少代码。

标签: javascript angularjs promise angular-promise


【解决方案1】:

您没有从$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; 
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2015-11-27
    • 2017-05-20
    • 2015-04-27
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多