【问题标题】:Angular JS Promise all sequentialAngular JS Promise 所有的顺序
【发布时间】:2019-03-17 21:52:49
【问题描述】:

我正在尝试使用 Promise 执行 3 个 Web 服务,并且我需要在所有这些 Web 服务都执行后,如果可能按顺序返回这 3 个服务的信息。 我有这个。

这是我的服务

getServices(url: string): Promise < any > {
  return this.http.get(CoordinadoresService.BASEURL + url)
    .toPromise()
    .then(response => {
      return response.json();
    })
    .catch(err => err);
}

这是我的组件

getOffices() {
  this.oficinas["coordinadores"] = [];
  let data = this.util.getLocalStorage("coordinadores");
  let promises = [];
  if (data != undefined) {
    for (let i = 0; i < Object.keys(data.coordinadores).length; i++) {
      let url = `getOficinas/${data.coordinadores[Object.keys(data.coordinadores)[i]].ip}/${Object.keys(data.coordinadores)[i]}`;
      promises.push(this.services.getServices(url).then(response => {
          response["coordinador"] = response.coordinador;
          this.oficinas["coordinadores"].push(response)
        },
        err => err));
    }

    Promise.all(promises).then(data => {
      console.log('Both promises have resolved', data);
    });
  }
}

但是他在这里给我未定义的回报。为什么?

Promise.all(promises).then(data => {
  console.log('Both promises have resolved', data);
});

谢谢。

【问题讨论】:

  • 使用HttpClientHttp ?
  • 您通过调用 then 来解开 Promise。所以你的 Promises 数组实际上不会有任何 Promise 这样的。
  • SiddAjmera 我使用 Http
  • 对不起,我不太明白。它的解决方案是什么?
  • “按顺序”是指三个承诺需要一个接一个地完成吗?

标签: javascript angular promise angular2-services


【解决方案1】:

您的实施存在一些问题。

  1. 首先,如果您使用HttpClient,则不必在回复时调用map,然后再调用json
  2. 您没有从this.services.getServices(url)then 返回。因此Promise.all 没有回复

以下是解决方法。


import { HttpClient } from '@angular/common/http';
...
constructor(private http: HttpClient) {}
....
getServices(url: string): Promise < any > {
  return this.http.get(CoordinadoresService.BASEURL + url)
    .toPromise();
}

getOffices() {
  this.oficinas["coordinadores"] = [];
  let data = this.util.getLocalStorage("coordinadores");
  let promises = [];

  if (data) {

    for (let i = 0; i < Object.keys(data.coordinadores).length; i++) {
      let url = `getOficinas/${data.coordinadores[Object.keys(data.coordinadores)[i]].ip}/${Object.keys(data.coordinadores)[i]}`;
      promises.push(this.getDataFromAPI(url));
    }

    Promise.all(promises).then(data => {
      console.log('Both promises have resolved', data);
    });
  }
}

private getDataFromAPI(url) {
  return this.services.getServices(url)
    .then(
      response => {
        response["coordinador"] = response.coordinador;
        this.oficinas["coordinadores"].push(response)
        return response;
      },
      err => err
    );
}

【讨论】:

  • 很高兴它有帮助。 :)
【解决方案2】:

console.log 中出现未定义的原因是这里的代码

  promises.push(this.services.getServices(url)
 .then(response => {
      response["coordinador"] = response.coordinador;
      this.oficinas["coordinadores"].push(response);
      // nothing returned
  }, err => err));

由于没有返回任何内容(如注明),推送到 Promise 中的 Promise 将解析为 undefined

只需添加一个return response

注意:response["coordinador"] = response.coordinador; 是多余的,就像说 a = a - 所以我不会在下面的代码中重复它

this.oficinas["coordinadores"] 也是 this.oficinas.coordinadores - 所以将使用后者

  promises.push(this.services.getServices(url)
 .then(response => {
      this.oficinas.coordinadores.push(response);
      // something returned
      return response;
  }, err => err));

至于你问题的另一部分......你想“按顺序”这样做

如果你可以使用async/await - 那将很容易改变

async getOffices() { // add async keyword
    this.oficinas.coordinadores. = [];
    let data = this.util.getLocalStorage("coordinadores");
    let results = []; // no longer dealing directly with promises, so lets rename this
    if (data != undefined) {
        for (let i = 0; i < Object.keys(data.coordinadores).length; i++) {
            let url = `getOficinas/${data.coordinadores[Object.keys(data.coordinadores)[i]].ip}/${Object.keys(data.coordinadores)[i]}`;
            // await the promise
            let result = await this.services.getServices(url).then(response => {
                this.oficinas.coordinadores.push(response);
                return response;
            }, err => err);
            // push the result
            results.push(result);
        }
        // output the result
        console.log('Both promises have resolved', results);
    }
}

而且-因为

let url = `getOficinas/${data.coordinadores[Object.keys(data.coordinadores)[i]].ip}/${Object.keys(data.coordinadores)[i]}`;

只是看起来很乱,让我建议一个替代方案

async getOffices() {
    this.oficinas.coordinadores. = [];
    let data = this.util.getLocalStorage("coordinadores");
    let results = [];
    if (data != undefined) {
        for (let [key, {ip}] of Object.entries(data.coordinadores)) {
            const url = `getOficinas/${ip}/${key}`;
            let result = await this.services.getServices(url).then(response => {
                this.oficinas.coordinadores.push(response);
                return response;
            }, err => err);
            results.push(result);
        }
        console.log('Both promises have resolved', results);
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2018-02-08
    • 2018-11-14
    • 2017-06-21
    • 2015-03-13
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2016-08-07
    相关资源
    最近更新 更多