链条循环承诺



我在查询数据库并插入数据时正在努力通过数组periods循环。我面临的问题可以在上线的第五次看到。最终的db.queryPromise不会被调用。

请参阅底部的评论5行,以了解问题的位置。

// db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : ****,
    password : ****,
    database : ****,
});
module.exports = connection;
module.exports.queryPromise = function (args) {
  return new Promise((resolve, reject) => {
    connection.query(args, (err, rows, fields) => {
      if (err) return reject(err);
      resolve(rows);
    });
  });
};
module.exports.connectPromise = new Promise((resolve, reject) => {
  connection.connect(err => {
    if (err) reject(err);
    resolve();
  });
});
// app.js
const db = require('../config/db');
const periods = ['1h','12h','24h','1w','1m','3m','1y','all'];
const sqlCarIds = `SELECT id FROM car_models ORDER BY id DESC LIMIT 200;`;
return db.queryPromise(sqlCarIds)
.then((rows) => {
  const car_ids = [];
  for (let i = rows.length - 1; i >= 0; i--) {
    car_ids.push(rows[i].car_id);
  };
  for (let i = periods.length - 1; i >= 0; i--) {
    const sqlSnapshot = `SELECT price FROM car_models;`;
    db.queryPromise(sqlSnapshot)
    .then(([row]) => {
      if (!row) {
        throw new Error('API call found nothin');
      }
      const highPrice = row.high;
      const sqlInsert = `INSERT into price_cache (high) VALUES (` + highPrice` + )`;`
      console.log(sqlInsert); // logs correctly formed query
      db.queryPromise(sqlInsert)
      .then(() => {
        console.log('this should fire'); // doesn't fire
      });
    });
  }
});

sqlInsert的SQL语法无效。您将需要像以下示例一样编写它。您需要使用${expression}文字将表达式的值添加到"模板字符串"中。您的承诺无法解决,因为有错误拒绝。

const sqlInsert = `INSERT into price_cache (high) VALUES (${highPrice})`;

最新更新