Асинхронный / ждущий запутанный код в Angular - неправильный порядок - PullRequest
0 голосов
/ 25 января 2020
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 внутри l oop. : /

1 Ответ

2 голосов
/ 25 января 2020

forEach не ожидает, пока каждый l oop выполнит асин c код, а также ваше обещание внутри l oop также не заставит l oop ждать.

for of l oop будет корректно ждать асин c функций, если вы будете ждать их, а не использовать формат обещания .then:

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;
}
...