javascript - 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 调用完成并返回一个值;
解决方案
您可以使用Promise.all
with map 并使用await
它。
map 将返回一个 Promises 数组,Promise.all
将等待所有 Promise 解析,然后将值解析为每个 Promise 的数组。
还要确保在异步函数中执行以下代码:
let componentRows = [...getState().formulaBuilder.componentRows];
componentRows = await Promise.all(componentRows.map(row => {
return _getSelectedComponentVariantByComponentName(row.name);
}));
推荐阅读
- wordpress - 如果选择了下拉选项之一,我需要显示自定义分类的帖子
- c++ - 使用 C++ 中的字符串向量调用 C API
- nlp - NLP 中用于检测网页中是否存在显着内容的任何工作
- pyspark - 在 PySpark 中将字典类型的列转换为多列
- git - 挤压和合并 VS 挤压和变基
- javascript - 在某些电子邮件上未收到带有 Firebase 电子邮件链接身份验证的登录电子邮件
- r - 条形图 + geom_jitter 与条形图填充内的抖动点
- amazon-web-services - 是否可以更改旧版本 S3 对象的文件扩展名?
- ios - 如何在 alertController 之后更新 tableView?
- spring-mvc - 如何在程序中手动使用spring @ProjectedPayload