2016-11-08 3 views
1

PersonModelオブジェクトのコレクションにpasswordという値をフォーマットするには、Javascript/Typescriptを使用しています。コレクションの各要素にPromiseを実行しています。Javascript Promise.all confusion

私はPromise.allを使用して、すべての約定を完了させてから、書式設定されたコレクションを戻したいと考えています。

ただし、ビルド時にエラーが発生します。

PersonService.ts

private decryptPersons(persons: PersonModel[]): Promise<PersonModel[]> { 
    return new Promise<PersonModel[]>(resolve => { 
     let promises: Array<Promise<string>> = []; 
     let decryptedPersons: PersonModel[] = []; 
     for (let i: number = 0; i < persons.length; i++) { 
      let ciphertext: string = persons[i].password; 
      promises.push(this.decrypt(ciphertext).then((password: string) => { // <== line 357 
       persons[i].password = password; 
       decryptedPersons.push(persons[i]); 
      })); 
     } 
     Promise.all(promises).then(() => { 
      resolve(decryptedPersons); 
     }); 
    }); 
} 

private decrypt(value: string): Promise<string> { 
    return new Promise<string>(resolve => { 
     this.encrypter.decrypt(value).then((result: string) => { 
      resolve(result); 
     }); 
    }); 
} 

エラー

ERROR in ./app/pages/service/personService.ts 
(357,31): error TS2345: Argument of type 'Promise<void>' is not assignable to parameter of type 'Promise<string>'. 
    Type 'void' is not assignable to type 'string'. 

私はJavaScriptを使用して何の専門家でないので、私の構造は私が間違ったことがあります。誰かが助言できるなら、私はそれを感謝します。

答えて

0

あなたのpromises配列にpushに次のことをしようとしている:

this.decrypt(ciphertext).then((password: string) => { // <== line 357 
    persons[i].password = password; 
    decryptedPersons.push(persons[i]); 
}) 

が、ここであなたの関数は何も返さないので、これはPromise<void>に評価しようとしています。

あなたはまた、ここのいくつかの場所で「明白な建設の反パターン」を乱用しています。

は、この試してみて:

private decryptPersons(persons: PersonModel[]): Promise<PersonModel[]> { 
    return Promise.all(persons.map(person => 
     this.decrypt(person.password) 
      .then(password => { 
       person.password = password; 
       return person; 
      }); 
    )); 
} 

private decrypt(value: string): Promise<string> { 
    return this.encrypter.decrypt(value); 
} 
+0

はあなたに感謝します。私は試してみます – Richard