Promise两种实现方式是否有差异?修改代码后担忧影响程序逻辑
Hey there! Let's break down the differences between your two implementations and figure out if the change impacts your program logic—spoiler: it does, but we can fix it easily.
Key Issues with Your Modified Code
Let's compare the two versions side by side to spot the problems:
1. Missing Promise Return When DB Exists
- Original code: Always returns a
Promiseinstance, regardless of whetherdbis available. Callers can reliably use.then()/.catch()to handle the outcome. - Modified code: When
dbexists, you calldb.executeSqlbut don't return anything from the function. This means anyone callingclearTableDemo()will getundefinedinstead of a Promise, breaking any subsequent Promise chain logic (like.then()to run code after the table is cleared).
2. Incorrect Promise Resolution in Callbacks
- Original code: Uses the
resolveandrejectfunctions passed to the Promise executor to properly update the Promise's state when the SQL operation completes or fails. This is the standard, correct way to control a Promise's lifecycle. - Modified code: Returning
Promise.resolve()orPromise.reject()insidedb.executeSql's callbacks does nothing useful. Those returned Promises are ignored byexecuteSql, so the caller never gets notified when the SQL operation finishes or errors out. The Promise chain just hangs here.
Fixed Version (Clean & Functional)
You can keep your improved early-exit structure while maintaining correct Promise behavior by wrapping the db.executeSql call in a Promise (like your original code) and returning it:
function clearTableDemo(tableName) { if (!db) return Promise.reject('db no open'); return new Promise((resolve, reject) => { db.executeSql(`DELETE FROM ${tableName}`, [], () => { resolve(); }, err => { reject(err); }); }); }
Note: I swapped the string concatenation for a template literal (${tableName}) for cleaner syntax—this doesn't change functionality, just readability.
Quick Summary
Your goal of making the code structure clearer is great, but the modified version breaks the Promise contract. The fixed version above keeps the clean early exit for the db check while ensuring the function always returns a valid Promise that properly signals the SQL operation's outcome.
内容的提问来源于stack exchange,提问作者Dicky Chan

