我有一个函数,可以在数据库的表“ 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获取insertd_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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句