用Node.js + CoffeeScript + MySQL做几个相关的插入

我有一个函数,它将一个URL和一个标题插入到我的数据库的表“url”中。 这个函数获取MySQL分配的id。 我会在下面解释我需要什么。

# Creates a URL in the database. create_url = (url, title) -> connection.connect print_err connection.query "INSERT IGNORE INTO url SET ?", {urlName: url, urlTitle: title}, (err, result) -> throw err if err inserted_id = result.insertId 

在我调用create_url之后,我想调用我的另一个函数,它插入到表'dailyUrl'中。

 create_daily_url = (url) -> connection.query "INSERT IGNORE INTO dailyUrl SET ?", {url: url}, (err, result) -> throw err if err inserted_id = result.insertId 

在这种情况下,参数url需要是我在前面的'create_url'函数中获得的'inserted_id'。

因此,我的主要脚本应该是这样的:

 create_url("www.test.com", "test") create_daily_url(inserted_id) 

我的问题是,我不知道如何从create_url中获取inserted_id以在主脚本中使用它。 任何帮助? 提前致谢。

您需要在create_url之后的callback中调用create_daily_url。 类似的东西:

 # Creates a URL in the database. create_url = (url, title,cb) -> connection.connect print_err connection.query "INSERT IGNORE INTO url SET ?", {urlName: url, urlTitle: title}, (err, result) -> throw err if err inserted_id = result.insertId cb result if typeof cb == "function" # prevent failures when you call this function without a callback create_url "www.test.com", "test", (inserted_url)-> create_daily_url inserted_url.id 

事实上,如果您将callback函数添加到create_daily_url函数中,将会非常有用。

 create_daily_url = (url,cb) -> connection.query "INSERT IGNORE INTO dailyUrl SET ?", {url: url}, (err, result) -> throw err if err inserted_id = result.insertId cb() if typeof cb == "function"