首页 > 解决方案 > 地图请求完成时解决承诺

问题描述

我正在处理书签页面,我们得到带有书签的餐厅 ID 的书签结果。然后我映射响应并将其作为对象推送到数组。

我想解析整个完成的数组,以便之后可以操作数据。

我创建了一个 getData 函数,它向书签 api 发出请求,在 onSucces 中我调用了一个名为 mapResult 的函数,如下所示:

mapResults(result: Array<any>, type: string): Promise<any> {
    const promise = new Promise<any>((resolve, reject) => {
        const requests = result.map((res, i) => {
            this.getRestaurantById(res.RestaurantId).then(restaurant => {
                const bookmarks = {
                     createdDate: res.CreatedDate,
                     restaurant: restaurant[0]
                };
                this.savedData[type].push(bookmarks);
            });
        });
        Promise.all(requests).then((completed) => {
            if(completed) {
                console.log(completed)
                resolve(this.savedData[type]);
            }
        })
    });
    return promise;
}

我订阅的地方是这样的:

this.mapResults(result, type).then(data => {
    console.log(data)
});

但是dataconsole.log 不是整个数据数组,它只会解析第一个对象。

为什么Promis.all函数不等待地图完成?

标签: javascripttypescriptobservable

解决方案


您的代码中有几个问题:

  • returnresult.map回调中什么都没有
  • new Promise没有必要
  • 您不应该使用状态变量而不是承诺返回值
  • 变量completed没有任何意义

此代码应按预期工作:

mapResults(result: Array<any>, type: string): Promise<any> {
    // you don't need "new Promise" as "getRestaurantById" already returns a promise itself

    const requests = result.map((res) => {
        // here you forgot to return something
        return this.getRestaurantById(res.RestaurantId).then(restaurant => {
            return {
                createdDate: res.CreatedDate,
                restaurant: restaurant[0]
            };
        });
    });

    // using "completed" did not make any sense as it is just an array filled with "undefined"s
    return Promise.all(requests).then((restaurants) => {
        console.log(restaurants)
        // TODO store "restaurants" in "this.savedData[type]" if needed
        return restaurants;
    });
}

推荐阅读