0

I have a code in Node js, which connects to a mysql database and inserts data, however, I have a problem, sometimes as it goes so fast, skips the steps, I would like it to just quit its function when it finishes to insert, do not go to the next instruction until you finish. Then I leave my code.

con.getConnection(function(err) {
  if (err) throw err;
  console.log("Conectado!");
});
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+"', ' ', '"+titulocomilla+"','', 'publish', 'open', 'closed','','"+zlug+"','','', '"+fhoy+"', '"+fhoy+"','', '"+co+"','','0', 'oposiciones','' ,0);";
  con.query(sql, function (err, result) {
    if (err) throw err;
    resolve(result);
    console.log("1 registro insertado");
  });
});
}

setTimeout(insertarpost, 1500);
setTimeout(obtenerultimopostid, 1500);

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+",'nº_plazas', '"+nplazascomilla+"'),("+result[0].ID+",'observaciones', '"+observacionescomilla+"'), ("+result[0].ID+",'descargar_documento_oficial', '"+linkdescarga+"'), ("+result[0].ID+",'plazo_de_instancias', '"+plazasincomilla+"'), ("+result[0].ID+",'ambito', '"+categoriacomilla+"'), ("+result[0].ID+",'tipo', '"+tipocomilla+"'), ("+result[0].ID+",'origen', '"+origencomilla+"'),("+result[0].ID+",'grupo', '"+grupocomilla+"'), ("+result[0].ID+",'fecha_de_publicacion', '"+fpublicacion+"'),  ("+result[0].ID+",'convocante', '"+convocantecomilla+"');";
  con.query(sql, function (err, result) {
    //if (err) throw err;
    console.log("1 registro wpmeta insertado");
  });

 var sql = "INSERT INTO wp_term_relationships (`object_id`, `term_taxonomy_id`, `term_order`) VALUES ("+result[0].ID+", '"+co+"', '0');";
  con.query(sql, function (err, result) {
    //if (err) throw err;
    console.log("1 registro de categoria insertado");
  });
});
}

1 Answers1

0

If I understood your Problem correctly you want to invoke the obtenerultimopostid function when the function insertarpost has been finished.

If it's the case you can use the Promise Object which you are returning from the insertarpost function:

insertarpost().then(obtenerultimopostid())
Silvers
  • 32
  • 2
  • 7