Dicky Chan
Dicky Chan

Reputation: 245

Is there any difference between these two approaches when using Promise?

I just changed my code to make the code look better. Is there any difference between these two approaches when using Promise? I am just afraid if it will affect the program logic. Thanks a lot.

Code Before changing:

function clearTableDemo(tableName) {
    return new Promise((resolve, reject) => {
        if (db) {
            db.executeSql('DELETE FROM '+ tableName, [],
                () => { resolve () },
                err => { reject() }
            );
        } else {
            reject('db no open');
        }
    });
}

Code After changing: (UPDATED)

function clearTableDemo(tableName) {
    if (!db) return Promise.reject('db no open');
    db.executeSql('DELETE FROM '+ tableName, [],
        () => { return Promise.resolve() },
        err => { return Promise.reject(err) }
    );
}

Upvotes: 0

Views: 64

Answers (1)

str
str

Reputation: 44969

The two functions are completely different, the second example does not return a Promise at all.

What you can do to simplify the function is, for example, the following code:

function clearTableDemo(tableName) {
    if (!db) {
        return Promise.reject('db no open');
    }
    return new Promise((resolve, reject) => {
        db.executeSql('DELETE FROM '+ tableName, [], resolve, reject);
    });
}

Upvotes: 6

Related Questions