Richard
Richard

Reputation: 8945

Javascript Uncaught Exception in Promise

I am using javascript and have the following function:

createChat(img1: string, img2: string): Promise<string> {
    return new Promise<string>((resolve) => {
        console.log('firebase craete');
        return this.af.database.list('/chat/').push({
            memberId1: this.me.uid,
            memberId2: this.you.uid,
            img1: img1,
            img2: img2,
            displayName1: this.me.displayName,
            displayName2: this.you.displayName,
            lastMsg_text: '',
            lastMsg_read1: true,
            lastMsg_read2: true,
            timestamp: Date.now(),
            negativtimestamp: -Date.now()
        }).then((item) => {
            console.log('firebase craete resolve', item.key);
            resolve(item.key);
        }).catch((error) => {
            console.error('Error creating chat', error);
        });
    });
}

and get the following output:

enter image description here

As you can see the Promise's resolve is being called, and it returns a value as expected. Do you know why I am getting the Exception?

Upvotes: 1

Views: 138

Answers (1)

Alnitak
Alnitak

Reputation: 339836

You've created a Promise anti-pattern, by wrapping your own Promise around a function that already returns a Promise (or Thenable)

You should:

  1. not catch the error there, but allow it to propagate upwards

  2. use .then internally to extract and return the field you require:

So:

createChat(img1: string, img2: string): ThenableReference<string> {
    return this.af.database.list('/chat/').push({
        memberId1: this.me.uid,
        memberId2: this.you.uid,
        img1: img1,
        img2: img2,
        displayName1: this.me.displayName,
        displayName2: this.you.displayName,
        lastMsg_text: '',
        lastMsg_read1: true,
        lastMsg_read2: true,
        timestamp: Date.now(),
        negativtimestamp: -Date.now()
    }).then(item => item.key);
}

NB: I'm not familiar with TypeScript, so the return type indicated above is probably incorrect.

Upvotes: 1

Related Questions