javascript - 我无法在 .then() Promise 中返回对象

标签 javascript mysql node.js promise

我创建了一个 ids 的对象,但是我无法在我的 for 之外或在我的 next .then () 中访问它,我将 det 作为全局变量,有人知道它错在哪里吗?

.then(function(idHome){

    home_id = idHome;

    var detname_img = [];
    var sqlEdit = "INSERT INTO images_det SET ?";

    for(var k = 0; k < object.det_img.length; k++){

        detname_img.push({
            name_img : object.det_img[k].name_img,
        });

        connection.query(sqlEdit,detname_img[k]);
    }

    // console.log(detname_img);

    for(var i = 0; i < detname_img.length; i++){

        var getDet = ("SELECT det_id from images_det where name_img = '" + detname_img[i].name_img + " ' order by 1 desc limit 1");

        connection.query(getDet, function(erro, result){

            for(var k = 0; k < result.length; k++){

                det.push({
                    det_id : result[k].det_id
                });
                console.log(chalk.blue(det[0].det_id));
                return det;
            }
        });
    }        

});

最佳答案

假设您使用 this Node mysql 包你可以从 result 中获取插入的 id插入语句。

由于该包似乎没有意识到 promise 的存在,您可以使用将返回 promise 的包装器清除 api:

//turn an insert query with callback function 
//  into a function returning a promise
const insertAsPromise = connection => args => 
  new Promise(
    (resolve,reject)=>
      //call connection query with variable amount of argument(s)
      //  using Function.prototype.apply
      connection.query.apply(connection,args.concat(
        //add the callback to the list of arguments, callback
        //  is the last argument
        (error, results, fields) =>
          (error)
            ? reject(error)
            : resolve([results,fields])
      ))
  );


const sqlEdit = "INSERT INTO images_det SET ?";
Promise.all(
  object.det_img.map(
    image=>//map magical/global object.det_img to promise
      insertAsPromise(connection)([sqlEdit,image.name_img])
      .then(//when promise resolves get the inserted id
        ([results,fields])=>
          results.insertId
      )
  )
)
.then(
  results=>console.log(results)//should log an array of id's
)
.catch(
  err=>console.error("something went wrong:",err)
)

关于javascript - 我无法在 .then() Promise 中返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483312/

相关文章:

php - 如何隐藏字符串中的 x 个字符

python - MySQL fetchall() - 如何在字典中而不是在元组中获取数据

node.js - NodeJS TCP Socket 不显示客户端主机名信息

node.js - 如何将 Node.js 与 Jemalloc 一起使用?

javascript - 如何在 react js 中动态更改网站的标题(也在源代码中)?

javascript - 删除类时不重置关键帧动画

mysql - 具有默认持久性提供程序的 ClassNotFoundException weblogic.jdbc.wrapper.JTSConnection?

c# - svg2png 性能

javascript - 无法在 PWA(react js) 中使用移动浏览器访问移动摄像头和麦克风

php - 使用 PHP/MySQL 上传 CSV