如何让回调函数在Promise后运行?Sequelize与MySQL包连接顺序问题
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:
Option 1: Promisify the callback-based MySQL connection (Recommended)
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

