1

I created an object of ids, however I can not access it outside of my for or in my next .then (), i make det as global variable, does anyone know where it is wrong?

.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;
            }
        });
    }        

});
gustavohenke
  • 40,997
  • 14
  • 121
  • 129
  • You don't appear to be returning it anywhere... – Alexander Nied Jan 28 '18 at 05:05
  • I tried to do ''return det'' and .then(something) console.log(someting) but does not work – Caio Pereira Jan 28 '18 at 05:07
  • 1
    Your `return det` is inside an async callback. That's not a return value from your `.then()` handler. You have NO return value from that function. Perhaps you need to read: [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). – jfriend00 Jan 28 '18 at 05:59
  • 1
    In addition, you should pretty much never use plain async callbacks inside a `.then()` handler for exactly this reason. Use the promise interface on your database (or promisify individual calls yourself) and then you can just return the promise directly. – jfriend00 Jan 28 '18 at 06:00
  • What is this doing: `connection.query(sqlEdit,detname_img[k]);` all by itself with no completion callback and no assignment of any result to anything? – jfriend00 Jan 28 '18 at 06:16

1 Answers1

0

Assuming you use this node mysql package you can get the inserted id from the result of the insert statement.

Since that package does not seem to be aware of the existence of promises you can dust off the api with a wrapper that will return a promise:

//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)
)
HMR
  • 37,593
  • 24
  • 91
  • 160