javascript - 使用 Node.js + CoffeeScript + MySQL 制作几个相关的插入

标签 javascript mysql node.js coffeescript

我有一个函数可以将 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/

相关文章:

javascript - 使用 Not Null 将 findAll 序列化

javascript - WP 菜单未按预期工作

javascript - 以 Angular 自动为页面的所有元素分配 ID

通过 shell 脚本的 MySQLDump 没有被执行,为什么?

php - CodeIgniter 或 Simple PHP,如何将一个表与另一个表的两列连接起来?

c# - 如何在 Entity Framework 连接字符串中设置转换零日期时间

javascript - 测试字符串是否有数字字符的条件

javascript - 如何访问使用外部样式表的 javascript 对象的样式属性?

node.js - webpack css-loader 在外部样式表的 url() 引用中找不到图像

javascript - 返回之前等待子函数执行