promise.all不能在拒绝功能中访问 [英] promise.all not access in rejection function

查看:130
本文介绍了promise.all不能在拒绝功能中访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个获取数据的服务,我用不同的参数调用了5次以获得不同的数据。
我调用了一个成功执行的函数:它运行正常。
但是如果失败的话,我需要做5个电话中的其他事情,而不是发生的事情:它总是进入成功功能。
我正在使用离子4角2
这是我的服务:

i have one service that get data , and i called it 5 times with different parametes to get different data. I called a function to execute in success case : it work fine. but in case of failure one from the 5 calls i need to do something else what's not happen : it always enter in success function. I'm using ionic 4 angular 2 this is the service i have :

 public getdataLookUps(type, lcid): Promise<string[]> {
return new Promise((resolve, reject) => {
  if (this.data[type + lcid]) {
    resolve(this.data[type + lcid]);
    return;
  }
  this.authService.getToken().then(
    (accessToken) => {
      let headers = new Headers({'Authorization': 'bearer ' + accessToken});
      let url = 'error url to test failure case';
      this.http.get(url, {headers: headers})
        .map(res => res.json())
        .toPromise()
        .then(
          (res) => {
            this.data[type + lcid] = res;
            resolve(res);
          },
          (error) => {
            reject(error);
          }
        );
    }
  );
});

}

然后我包装了这个函数它调用这样的服务:(用不同的参数重复5次):

then I wrapper the function that calls the service like this: ( repeated 5 times with different params):

public getAreas() {
    return this.lookupsService.getdataLookUps('Region', this.lcid).then(
      (res) => {
        this.areas = res;
      },
      () => {
        //todo
return Promise.reject('rejection error');
      }
    );
  }

然后我调用5个函数:

  ngOnInit() {
    this.getCaseCategories();
    this.getAreas();
    this.getWeather();
    this.getMifonProjects();
    this.getUserInfo();
}

我在这里做promise.all():

and I do promise.all() here :

ngAfterViewInit(){
 Promise.all(
      [
        this.getCaseCategories(),
        this.getAreas(),
        this.getWeather(),
        this.getMifonProjects(),
        this.getUserInfo(),
      ]
    ).then(
      () => {
        this.loadMap();
      },
      () => {
        this.showErrorMessage = true;
      }
    );
}


推荐答案

此代码有两个回调函数然后,成功处理程序和错误处理程序。如果代码如您所示,错误处理程序返回成功结果,那么 Promise.all()将始终成功:

This code has two callbacks for then, a success handler, and an error handler. If the code is as you have shown the error handler returns a success result so your Promise.all() will always succeed:

public getAreas() {
    return this.lookupsService.getdataLookUps('Region', this.lcid).then(
      (res) => {
        this.areas = res;
      },
      () => {
        //todo
      }
    );
  }

除非你真的能够处理错误,否则不要添加错误处理程序这里。而只是让错误传播到下一个处理程序:

Don't add an error handler unless you are really able to handle the error here. Instead just let the error propagate out to the next handler:

public getAreas() {
    return this.lookupsService.getdataLookUps('Region', this.lcid)
    .then(res => this.areas = res);
  }

现在你的 Promise.all 会给你一个错误。

Now your Promise.all will give you an error when the data lookup fails.

同样停止嵌套你的承诺处理程序:

Also stop nesting your promise handlers:

public getdataLookUps(type, lcid): Promise<string[]> {
    if (this.data[type + lcid]) return Promise.resolve(this.data[type + lcid]);
    return this.authService.getToken().then(
      (accessToken) => {
        let headers = new Headers({'Authorization': 'bearer ' + accessToken});
        let url = 'error url to test failure case';
        return this.http.get(url, {headers: headers})
          .map(res => res.json())
          .toPromise();
     })
     .then((res) => this.data[type + lcid] = res);
}

一旦你有承诺只需返回 Promise 就不需要创建新的Promise了。如果您的promise成功处理程序创建另一个promise,则返回以避免嵌套。您的错误处理程序除了传播错误之外什么也没做,所以当您没有嵌套的承诺时,您也不需要它,只需让错误自然传播。

Once you have a Promise just return the Promise there is no need to create a new Promise. And if your promise success handler creates another promise return that to avoid nesting. Your error handler did nothing but propagate the error, so when you don't have the nested promise you don't need that either, just let the error propagate naturally.

这篇关于promise.all不能在拒绝功能中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆