【问题标题】:async/wait confusing code in Angular - the order is wrongAngular 中的异步/等待混淆代码 - 顺序错误
【发布时间】:2020-05-11 07:51:43
【问题描述】:
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 请求的响应后才返回数组。 :/

【问题讨论】:

    标签: angular asynchronous promise async-await


    【解决方案1】:

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

    如果您等待异步函数而不是使用 .then 承诺格式,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;
    }
    

    【讨论】:

    • 为什么 forEach 不等待 async 而 for of 会等待 async ?
    • @SatishPai 因为 forEach 的实现只是一个 for 循环,但它不等待回调
    猜你喜欢
    • 2015-11-06
    • 2019-01-23
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多