我有一个函数可以将 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 之后的回调中调用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
确实,如果您向 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"
关于javascript - 使用 Node.js + CoffeeScript + MySQL 制作几个相关的插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444814/