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

如何让回调函数在Promise后运行?Sequelize与MySQL包连接顺序问题

How to make a callback-based MySQL connection wait for a Promise-based Sequelize connection?

The issue here is that your two immediately-invoked function expressions (IIFEs) run in parallel. The Sequelize connection uses async/await (which is promise-based and asynchronous under the hood), while the manual MySQL connection uses a callback that fires as soon as the connection attempt starts—so it doesn't wait for the Sequelize promise to resolve.

Here are two clean ways to fix this and ensure the manual MySQL connection only runs after Sequelize has successfully connected:

Wrap the callback-style connect method in a Promise, then use await to run it sequentially after the Sequelize connection. This keeps your code flat and avoids callback hell if you have more async operations later.

const db = require('./config/db');
const dbManual = require('./config/dbManual');

// Convert the callback-based connect to a Promise
const connectManualDb = () => {
  return new Promise((resolve, reject) => {
    dbManual.connect(err => {
      if (err) reject(err);
      else resolve();
    });
  });
};

(async () => {
  try {
    // Wait for Sequelize to connect first
    await db.authenticate();
    console.log('database connected with "sequelize" package');
    
    // Now connect with the manual MySQL package
    await connectManualDb();
    console.log('database connected with "mysql" package');
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
})();

Option 2: Nest the MySQL connection inside the Sequelize success block

If you don't want to promisify the callback, you can simply move the manual connection call inside the try block after the Sequelize await. This ensures it only runs once Sequelize has connected successfully.

const db = require('./config/db');
const dbManual = require('./config/dbManual');

(async () => {
  try {
    await db.authenticate();
    console.log('database connected with "sequelize" package');
    
    // Execute the manual connection only after Sequelize succeeds
    dbManual.connect(err => {
      if (err) {
        console.error(err);
        process.exit(1);
      } else {
        console.log('database connected with "mysql" package');
      }
    });
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
})();

Why your original code didn't work

Your original code has two separate IIFEs that start at the same time. The async IIFE with Sequelize runs asynchronously (the await pauses inside that function, but doesn't block the rest of the code), so the second IIFE with the callback-based MySQL connection starts immediately and completes first.

内容的提问来源于stack exchange,提问作者max23701

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:54:03