首页 > 解决方案 > JavaScript:如何等待异步 api 调用完成

问题描述

我有一个异步功能:

 const _getSelectedComponentVariantByComponentName = async (name) => {
            const response = await api.get(`/internal/api/Component/GetComponentVariantByComponentName/${name}`);

            componentRow.component = response.data;
            return componentRow;
        };

我正在尝试在.map()方法中使用这个函数:

let componentRows = [...getState().formulaBuilder.componentRows];
componentRows = componentRows.map(async row => {
                row  = await _getSelectedComponentVariantByComponentName(row.name);
                return row;
            });

但在这种情况下,我得到了一个状态为“待定”的 Promise。如何等待异步 api 调用完成并返回一个值;

标签: javascriptpromiseasync-await

解决方案


您可以使用Promise.allwith map 并使用await它。

map 将返回一个 Promises 数组,Promise.all将等待所有 Promise 解析,然后将值解析为每个 Promise 的数组。

还要确保在异步函数中执行以下代码:

 let componentRows = [...getState().formulaBuilder.componentRows];
  componentRows = await Promise.all(componentRows.map(row => {
            return _getSelectedComponentVariantByComponentName(row.name);
        }));

推荐阅读