Richard
Richard

Reputation: 8935

Javascript Promise calling a Promise confusion

I am using Javascript/Typescript to create a Promise that returns and PersonModel object that is formatted. However I am getting build errors:

PersonService.ts

private encryptPerson(person: PersonModel): Promise<PersonModel> {
    return new Promise<PersonModel>(resolve => {  // <== line 332
        let password: string = person.password;
        this.encrypt(password).then((ciphertext: string) => {
            person.password = ciphertext;
            resolve(person);
        });
    },
        error => {
            console.error(error)
        });
}

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

Error

ERROR in ./app/pages/service/personService.ts
(332,16): error TS2346: Supplied parameters do not match any signature of call target.

Any help of how I should structure this appreciated.

UPDATE

After advise from T.J. Crowder below, I have got the following:

private encryptPerson(person: PersonModel): Promise<PersonModel> {
    return new Promise<PersonModel>(resolve => {
        let password: string = person.password;
        this.encrypt(password).then((ciphertext: string) => {
            person.password = ciphertext;
            resolve(person);
        });
    });
}

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

Upvotes: 1

Views: 51

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

You're calling the Promise constructor with two arguments:

private encryptPerson(person: PersonModel): Promise<PersonModel> {
    return new Promise<PersonModel>(resolve => { // <== line 332
            let password: string = person.password;
            this.encrypt(password).then((ciphertext: string) => {
                person.password = ciphertext;
                resolve(person);
            });
        },
        error => {                  // ** This is the
            console.error(error)    // ** second argument
        });                         // ** to the constructor
}

It only takes one argument. I suspect that second arrow function was meant to be attached to the then inside the first one.

Separately, if I'm correct about where you meant that second function to go, beware that it converts a rejection into a resolution using undefined as the resolution value. Since undefined isn't a PersonModel, I'm guessing that's going to be a problem as well.

Upvotes: 2

Related Questions