Обещание всех - необработанное отклонение обещания - PullRequest
0 голосов
/ 04 сентября 2018

Делая некоторые TTD и пытаясь выдать пользовательское исключение, которое я назвал FailedToConnectError, но я продолжаю получать мой NoAccountFoundError.

Вот мой тест:

Server.SERVER_URL = 'http://www.test.com.fail';

server.getAccounts(['999999999']).catch(e=>{
    expect(e).toBeInstanceOf(FailedToConnectError);
});

Главное в следующей функции - это сгруппировать идентификаторы учетных записей в группы по 100, а затем создать массив обещаний для выполнения. (API позволяет одновременно просматривать до 100 учетных записей):

public getAccounts(accountIDs: string[]): Promise<Account[]>{   
    return new Promise<Account[]>((resolve, reject) => { 
        let groupedAccountIds:string[] = this.groupAccountIdsByMaxRquestLimit(accountIDs);
        let promises: Promise<Account[]>[] = this.buildPromisesForGroupingAccounts(groupedAccountIds:string);

        Promise.all(promises).then(accountProfilePromises => {
            let accounts:Account[] = [];

            for(let accountProfiles of accountProfilePromises){
                for(let accounts of accountProfiles){
                    accounts.push(accounts);
                }
            }

            if(accounts.length < 1){
                reject(new NoAccountFoundError());
            }

            resolve(accounts);
        }).catch(err => {
            reject(err);
        });

    });
}

Вот buildPromisesForGroupingAccounts, когда также вызывается функция для отправки http-запроса.

private buildPromisesForGroupingAccounts(groupedIds:string[]){
    let promises: Promise<Account[]>[] = [];

    for(let accountIdsBy100s of groupedIds){
        let get100Accounts = new Promise<Account[]>((resolve, reject) => {
            var path = 'accounts/?'+'accounts='+accountIdsBy100s;
            this.websiteRequest(path, reject, (r:any,body:any)=>{
                  let accountsJSON = JSON.parse(body).response.players;

                  let accounts:Account[] = [];

                  for(let account of accountsJSON){
                      accounts.push(account);
                  }

                  resolve(accounts);
            });
        });

        promises.push(get100Accounts);
    }

    return promises;
}

Вот функция запроса веб-сайта:

public websiteRequest(path:string, reject: Function, cb: Function){
    request.get({
        url:Server.SERVER_URL+path
      }, 
      async (err,r,body) => {
          if(err){
            reject(new FailedToConnectError());
          }else{
            cb(r,body);
          }
      });
}

Наконец, это ошибка, которую я получаю, когда запускаю свой код:

(node:3835) UnhandledPromiseRejectionWarning: Error: expect(value).toBeInstanceOf(constructor)
Expected constructor: FailedToConnectError
Received constructor: NoAccountFoundError
Received value: [Error: No account found]
(node:3835) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3835) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
...