完成地图请求后解决承诺

问题描述 投票:-1回答:2

我正在处理书签页面,我们得到带有书签的餐馆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)
});

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

为什么Promis.all功能不等待地图完成?

javascript typescript observable
2个回答
3
投票

您的代码中有几个问题:

  • 你在return回调中没有任何result.map
  • new Promise没有必要
  • 您不应该使用状态变量而不是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;
    });
}

0
投票

您不会在地图中返回您的承诺。

© www.soinside.com 2019 - 2024. All rights reserved.