等待它解决诺言,然后整齐地插入 [英] Wait for it to resolve promise and then insert neatly

查看:52
本文介绍了等待它解决诺言,然后整齐地插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整个上午都在看,因为此代码对我不起作用.

I've been watching all morning because this code doesn't work for me.

我希望一旦解决了诺言,那么"将获取其最后插入的ID(诺言)并整齐地插入另一个表中.目前,首先是兑现了所有的承诺,然后又是无序的...

I want once the promise is resolved, the "then" get its last inserted ID (the promise) and neatly insert into the other table. Currently first paints all the promise and then just then or disorderly ...

con.query("SELECT ID FROM wp_posts ORDER BY ID DESC LIMIT 0,1;", function(err, result, fields) {
  console.log(result);
  for (var i = 0; i < getData.length; i++) {
    var source = getData[i]["source"];
    var text = getData[i]["text"];
    var quality = getData[i]["quality"];
    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 + "', '', '" + make + "','', 'publish', 'closed', 'closed','','" + make + "','','', '" + fhoy + "', '" + fhoy + "','', '" + result[0].ID + "','','0', 'dt_links','' ,0);";
      con.query(sql, function(err, result) {
        if (err) throw err;
        resolve(result);
        console.log("1 registro link insertado");
      });
    }).then(function() {
      //new Promise(function(resolve, reject) {
      con.query("SELECT ID FROM wp_posts WHERE post_type='dt_links' ORDER BY ID DESC LIMIT 0,1;", function(err, result, fields) {
        console.log(result);
        var sql = "INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES (" + result[0].ID + ",'_dool_url', '" + source + "'),(" + result[0].ID + ",'_dool_type','" + text + "'),(" + result[0].ID + ",'_dool_quality','" + quality + "');";

        con.query(sql, function(err, result) {
          if (err) throw err;
          console.log("1 registro link meta insertado");
        });
        // });
      });
    });
  }
});

推荐答案

下面是一个示例,说明了如果使用mysql2中内置的基于promise的接口正确地对所有操作进行排序,则可以使事情变得更加简洁:

Here is an example of how much cleaner things can be if you use the promise-based interface built into mysql2 to sequence all your operations properly:

// using mysql2/promise
// parent function must be declared async

try {
    let posts = await con.query("SELECT ID FROM wp_posts ORDER BY ID DESC LIMIT 0,1;");
    console.log(posts);
    for (const post of posts) {
        const source = post.source;
        const text = post.text;
        const quality = post.quality;

        let 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 + "', '', '" + make + "','', 'publish', 'closed', 'closed','','" + make + "','','', '" + fhoy + "', '" + fhoy + "','', '" + posts[0].ID + "','','0', 'dt_links','' ,0);";
        await con.query(sql);
        console.log("1 registro link insertado");

        let result = con.query("SELECT ID FROM wp_posts WHERE post_type='dt_links' ORDER BY ID DESC LIMIT 0,1;")
        console.log(result);

        sql = "INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES (" + result[0].ID + ",'_dool_url', '" + source + "'),(" + result[0].ID + ",'_dool_type','" + text + "'),(" + result[0].ID + ",'_dool_quality','" + quality + "');";
        await con.query(sql);
        console.log("1 registro link meta insertado");
    }
} catch(e) {
    // handle all db errors here
}

这不仅易于阅读和理解,而且还对每个数据库操作进行排序,并将所有错误处理收集到一个位置(以前您基本上没有错误处理).

Not only is this a lot simpler to read and understand, but it also sequences each of your database operations and collects all the error handling to one place (you had basically no error handling before).

更改列表:

  1. 切换到mysql2/promise,以便我们可以使用内置的promise接口.
  2. 使用 async await 使排序异步数据库操作更容易编写代码
  3. 使用 try/catch 在一处捕获并处理所有数据库错误(您之前没有进行过合理的错误处理)
  4. 切换到 for/of 作为迭代数组的更便捷方法
  5. 适当地用 const let 替换所有 var 声明.
  6. 将语法从类似 getData [i] ["quality"] 的内容切换为 getData [i] .quality ,因为它更简单,并且不需要引号和方括号一个简单的属性名称.
  1. Switch to mysql2/promise so we can use the built-in promise interface.
  2. Use async and await to make sequencing asynchronous database operations a lot simpler to code
  3. Use try/catch to catch and handle all database errors in one place (you had no reasonable error handling before)
  4. Switch to for/of as a more convenient way to iterate an array
  5. Replace all var declarations with const or let as appropriate.
  6. Switch syntax from things like getData[i]["quality"] to getData[i].quality because it's just simpler and the quotes and brackets are not needed around a simple property name.

未解决的问题:

  1. 您在 for 循环中的第一个查询每次都完全相同.这似乎是不正确的.该原始查询中对 result 的唯一引用是 result [0] .ID ,但每次循环时该值将完全相同,因此显然不正确接着就,随即.我不希望您每次都希望在循环中插入相同的记录.
  1. Your first query in the for loop is exactly the same every time through the loop. That does not seem correct. The only reference to result in that original query was result[0].ID, but that will be exactly the same value every time through the loop so something is apparently not correct with that. I don't think you want to be inserting the same record everytime through the loop.

这篇关于等待它解决诺言,然后整齐地插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆