【问题标题】:Wait for it to resolve promise and then insert MySQL等待它解析promise,然后插入MySQL
【发布时间】:2020-06-26 06:48:03
【问题描述】:

我在 Nodejs 中有代码,它将首先插入一个帖子,然后是一个元帖子(其他表)。

我希望先插入帖子,然后搜索最后一个 ID 并插入元帖子(其他表)。

但它不起作用,它似乎没有等待第一个函数插入帖子。

这是我的代码:

function insertarpost() { 
    return new Promise(function(resolve, reject) { 
        var sql = "INSERT INTO `wp_posts` ( `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`,`post_excerpt`, `post_status`,`comment_status`, `ping_status`,`post_password`, `post_name`,`to_ping`,`pinged`, `post_modified`, `post_modified_gmt`,`post_content_filtered`,`post_parent`, `guid`,`menu_order`, `post_type`, `post_mime_type`,`comment_count`) VALUES (1, '"+fhoy+"', '"+fhoy+"', ' ', '"+title+"','', 'publish', 'open', 'closed','','"+slug+"','','', '"+fhoy+"', '"+fhoy+"','', '0','','0', 'movies','' ,0);"; 
        con.query(sql, function (err, result) { 
            if (err) throw err; 
            resolve(result); 
            console.log("1 registro insertado"); 
        }); 
    }); 
}

insertarpost().then(obtenerultimopostid())

function obtenerultimopostid() {
    con.query("SELECT ID FROM wp_posts ORDER BY ID DESC LIMIT 0,1;", function (err, result, fields) {
        var sql = "INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES ("+result[0].ID+",'runtime', '"+runtime+"'),("+result[0].ID+",'original_title','"+titleoriginal+"'),("+result[0].ID+",'Rated','"+cpgrated+"'),("+result[0].ID+",'Country', '"+country+"'),("+result[0].ID+",'date', '"+datemovie+"'),("+result[0].ID+",'imdbRating', '"+repimdb+"'),("+result[0].ID+",'vote_average', '"+reptmdb+"'),("+result[0].ID+",'imdbVotes', '"+quantimdb+"'),("+result[0].ID+",'vote_count', '"+quanttmdb+"'),("+result[0].ID+",'tagline', '"+tagline+"'),("+result[0].ID+",'dt_poster', '"+poster+"');"; 
        con.query(sql, function (err, result) { 
            if (err) throw err; 
            console.log("1 registro wpmeta insertado");
        });
    });
}

【问题讨论】:

    标签: javascript mysql node.js wordpress


    【解决方案1】:

    您正在执行第二个函数,而不是函数传递给then 方法:

    变化:

    insertarpost().then(obtenerultimopostid())
    

    到:

    insertarpost().then(obtenerultimopostid)
    

    不是您的问题,但您的代码容易受到SQL injection 的攻击。

    【讨论】:

    • 非常感谢,你真是太好了。
    猜你喜欢
    • 2017-09-10
    • 1970-01-01
    • 2018-09-20
    • 2020-01-27
    • 2021-08-03
    • 1970-01-01
    • 2016-09-15
    • 2022-10-05
    • 1970-01-01
    相关资源
    最近更新 更多