JavaScript:如何等待异步api调用完成
我有一个异步函数:JavaScript:如何等待异步api调用完成,javascript,promise,async-await,Javascript,Promise,Async Await,我有一个异步函数: const _getSelectedComponentVariantByComponentName = async (name) => { const response = await api.get(`/internal/api/Component/GetComponentVariantByComponentName/${name}`); componentRow.component = response.data;
const _getSelectedComponentVariantByComponentName = async (name) => {
const response = await api.get(`/internal/api/Component/GetComponentVariantByComponentName/${name}`);
componentRow.component = response.data;
return componentRow;
};
let componentRows = [...getState().formulaBuilder.componentRows];
componentRows = await Promise.all(componentRows.map(row => {
return _getSelectedComponentVariantByComponentName(row.name);
}));
我试图在.map()方法中使用此函数:
let componentRows = [...getState().formulaBuilder.componentRows];
componentRows = componentRows.map(async row => {
row = await _getSelectedComponentVariantByComponentName(row.name);
return row;
});
但在这种情况下,我得到了一个状态为“待定”的承诺。
如何等待异步api调用完成并返回值 您可以使用Promise.all
和map并使用wait
map将返回一个承诺数组,Promise。all
将等待所有承诺解析,然后将值解析为每个承诺的数组
另外,请确保在异步函数中执行以下代码:
const _getSelectedComponentVariantByComponentName = async (name) => {
const response = await api.get(`/internal/api/Component/GetComponentVariantByComponentName/${name}`);
componentRow.component = response.data;
return componentRow;
};
let componentRows = [...getState().formulaBuilder.componentRows];
componentRows = await Promise.all(componentRows.map(row => {
return _getSelectedComponentVariantByComponentName(row.name);
}));
您可以使用Promise.all
和map并使用wait
map将返回一个承诺数组,Promise。all
将等待所有承诺解析,然后将值解析为每个承诺的数组
另外,请确保在异步函数中执行以下代码:
const _getSelectedComponentVariantByComponentName = async (name) => {
const response = await api.get(`/internal/api/Component/GetComponentVariantByComponentName/${name}`);
componentRow.component = response.data;
return componentRow;
};
let componentRows = [...getState().formulaBuilder.componentRows];
componentRows = await Promise.all(componentRows.map(row => {
return _getSelectedComponentVariantByComponentName(row.name);
}));
使用等待承诺。全部(数组)
是否确实要一致地等待每个项目?看起来是承诺的完美用例。所有的都回答了你的问题吗?使用等待承诺。全部(数组)
是否确实要一致地等待每个项目?看起来是承诺的完美用例。所有的都回答了你的问题吗?回答很好,但我认为它需要更多的信息:异步函数总是返回一个承诺,map函数返回从内部回调返回的任何内容的数组,这是一个承诺,因此,在js中,我们可以使用Promise在数组中等待所有承诺的解析。all
回答得很好,但我认为它需要更多的信息:异步函数总是返回一个承诺,map函数返回从内部回调返回的任何内容的数组,这是一个承诺,因此,在js中,我们可以使用Promise.all