当我尝试将数据推送到 Algolia 时遇到问题

I have a problem when I try to push the data to Algolia

我正在尝试将 Mysql 中的数据库数据推送到 Algolia。 这是代码。

const algoliasearch = require("algoliasearch");
const client = algoliasearch(ALGOLIA_APPLICATION_ID, ALGOLIA_ADMIN_API_KEY);
const index = client.initIndex("demo_ecommerce");
const _ = require('lodash');

var mysql = require('mysql');

var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : 'password',
    database : 'ecommerce'
})

connection.connect();

connection.query("SELECT * FROM productos", (err, res) => {
  if (err) throw err;
  const chunks = _.chunk(res, 1000)
  chunks.forEach(chunk => index.saveObjects(chunk))
});

connection.end();

但是当我 运行 代码时,我收到了这个错误。

(node:8900) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, 
use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8900) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

可以帮我解决这个问题吗?我需要做什么来解决它?

您似乎要在查询完成前关闭 connection。删除 connection.end() 并查看是否有帮助。

您看到 UnhandledPromiseRejectionWarning 是因为您在回调内部使用 throw err 而不是在任何地方处理它。

相反,尝试记录它以查看实际错误是什么并以适合您的应用程序的方式正确处理它。

首先:您的 connection.connect() 不会立即完成。相反,它使用回调来宣布其完成。但是你没有。

不过没关系,因为 connection.query() 隐式连接。所以去掉 connection.connect()connection.end() 。你不需要他们。

其次,您有行 if (err) throw err; 如果您的代码包含在 try / catch 处理程序中,该行将很有用。但事实并非如此。因此,当您抛出错误时,事情就会中断。而是做这样的事情:

if (err) {
  console.error(err)
  return
}

当 MySQL 将一个踢回给你时,你会看到错误。

第三,您误用了 algolia 包中的 the .saveObjects() method。该方法 returns 是一个 Promise,但您无需使用 .then()await.

等待它

您想遍历数组,为每个块调用 .saveObjects()。这是最直接的方法,使用带有普通 for 循环的异步函数。

connection.query("SELECT * FROM productos", (err, res) => {
  if (err) {
    console.error(err)
    return
  }
  saveAllObjects (res)
  .then (i => console.log (i, 'chunks saved.))
  .catch (err => console.error (err))
});

async function saveAllObjects (res) {
  const chunks = _.chunk(res, 1000)
  for (let i = 0; i < chunks.length; i++) {
    await index.saveObjects(chunks[i])
  }
  return chunks.length
}

此公式让您的异步函数在开始下一个操作之前等待每个 .saveObjects() 操作的完成。

要有耐心:让你的大脑围绕 Javascript 的异步特性进行思考需要时间。