异步/等待 Angular 中令人困惑的代码 - 顺序错误


async getRequest(node_id, uri, params) {
var children_nodes = [];
const request_response: any = await this.http.get(uri, {params: params}).toPromise();
request_response.children.forEach(element => {
children_nodes.push({'node_id': element.node_id});
});
return children_nodes;
}
async myMainFunction(node_ids) {
let fetch_all_node_ids = async () => {
var children_nodes = [];
node_ids.forEach(node_id => {
var uri = some_url;
var param = some_params;
console.log('calling this.getRequest');
this.getRequest(node_id, uri, param).then((children_nodes: any) => {
children_nodes.forEach(node_dict => {
console.log('pushing into children_nodes:', node_dict);
children_nodes.push(node_dict);
})
});
});
return children_nodes;
};
const children_nodes = await fetch_all_node_ids();
console.log('before finishing myMainFunction: ', children_nodes);
return children_nodes;
}

我是 Angular 的新手,我被困在这里:

为什么我先进入我的主机

before finishing myMainFunction: ...

然后:

pushing into children_nodes:

我只想在循环内填充了 get 请求的响应时才返回数组。

forEach

不会等待每个循环执行异步代码,而且您在循环中的承诺也不会使循环等待。

如果您等待异步函数而不是使用.thenpromise 格式,则for of循环将正确等待异步函数:

async myMainFunction(node_ids) {
let fetch_all_node_ids = async () => {
var children_nodes = [];
for (const node_id of node_ids) {
var uri = some_url;
var param = some_params;
console.log('calling this.getRequest');
const children_nodes = await this.getRequest(node_id, uri, param)
children_nodes.forEach(node_dict => {
console.log('pushing into children_nodes:', node_dict);
children_nodes.push(node_dict);
})
}
return children_nodes;
};
const children_nodes = await fetch_all_node_ids();
console.log('before finishing myMainFunction: ', children_nodes);
return children_nodes;
}

最新更新