You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Promise instance, regardless of whether db is available. Callers can reliably use .then()/.catch() to handle the outcome.
  • Modified code: When db exists, you call db.executeSql but don't return anything from the function. This means anyone calling clearTableDemo() will get undefined instead 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 resolve and reject functions 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() or Promise.reject() inside db.executeSql's callbacks does nothing useful. Those returned Promises are ignored by executeSql, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:40:37