Angular 异步/等待混淆角度的代码-顺序错误
我不熟悉Angular,我被困在这里: 为什么我要先进入控制台Angular 异步/等待混淆角度的代码-顺序错误,angular,asynchronous,promise,async-await,Angular,Asynchronous,Promise,Async Await,我不熟悉Angular,我被困在这里: 为什么我要先进入控制台 在完成MyMain函数之前:… 然后: 推入子节点: 我只想在循环中填充get请求响应后返回数组:/ forEach不会等待每个循环执行异步代码,而且您在循环内的承诺也不会让循环等待 如果您等待异步函数而不是使用,of的循环将正确等待它们。然后承诺格式: async getRequest(node_id, uri, params) { var children_nodes = []; const request_re
在完成MyMain函数之前:…
然后:
推入子节点:
我只想在循环中填充get请求响应后返回数组:/
forEach
不会等待每个循环执行异步代码,而且您在循环内的承诺也不会让循环等待
如果您等待异步函数而不是使用,of的循环将正确等待它们。然后承诺格式:
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;
}
forEach
不会等待每个循环执行异步代码,而且循环内的承诺也不会让循环等待
如果您等待异步函数而不是使用,of的循环将正确等待它们。然后承诺格式:
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;
}
为什么forEach不等待async,for of将等待async?@SatishPai因为forEach的实现只是一个for循环,但它不等待回调为什么forEach不等待async,for of将等待async?@SatishPai因为forEach的实现只是一个for循环,但它不等待回调回拨