需要帮助让 Promise.all 在 Angular 中工作

Dan*_*ase 3 angular

到目前为止,我一直在创建直接从 HTTP get 返回的函数,然后调用.subscribe返回值。然而,最近我了解了Promise.all,并且想知道如何使用它来等待两个 HTTP 获取完成。

我目前正在做的示例:

function getCustomerList() {
 return this.http.get("http://myapi.com/getCustomerList");
}

function otherFunction() {
  this.getCustomerList().subscribe() {
    data => {}, err => {}, () => {}
  }
}

Run Code Online (Sandbox Code Playgroud)

这似乎工作正常,但我一直想知道我是否可以做这样的事情:

function getCustomerList() {
  return this.http.get("http://myapi.com/getCustomerList").subscribe( data => {}, err => {}, () => {});
}

function getVendorList() {
  return this.http.get("http://myapi.com/getVendorList").subscribe( data => {}, err => {}, () => {});
}

function getAllInfo() {
  var p1 = getCustomerList();
  var p2 = getVendorList();

  Promise.All([p1, p2]);
  console.log("This should not run until both have returned");
}

Run Code Online (Sandbox Code Playgroud)

但它总是立即运行。所以我尝试.toPromise()get()函数中使用.then(),它做了同样的事情。我唯一没有尝试过的可能是.toPromise()在外部函数上添加一个。

ino*_*nik 5

他们立即跑掉的原因是因为你退回了订阅。你可以这样做:

function getCustomerList() {
  return this.http.get("http://myapi.com/getCustomerList").toPromise();
}

function getVendorList() {
  return this.http.get("http://myapi.com/getVendorList").toPromise();
}

function getAllInfo() {
  const p1 = getCustomerList();
  const p2 = getVendorList();

  Promise.all([p1, p2]).then(values => {
    console.log("This should not run until both have returned", values);
  });
}
Run Code Online (Sandbox Code Playgroud)

但更好的是,您可以使用forkJoin

import { forkJoin } from 'rxjs';

// component declaration and constructor omitted

customerList$ = this.http.get("http://myapi.com/getCustomerList");
vendorList$ = this.http.get("http://myapi.com/getVendorList");

getAll() {
  forkJoin(this.customerList$, this.vendorList$).subscribe(result => {
    console.log(result);
    // [{ customerList: ... }, {vendorList: ... }];
  });
}
Run Code Online (Sandbox Code Playgroud)