簡體   English   中英

等待它解決promise然后插入MySQL

[英]Wait for it to resolve promise and then insert MySQL

我在 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");
        });
    });
}

您正在立即執行第二個函數,而不是函數傳遞then方法:

改變:

insertarpost().then(obtenerultimopostid())

到:

insertarpost().then(obtenerultimopostid)

不是你的問題,但你的代碼容易受到SQL injection 的影響

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM