0

I'm having problems trying to "loop" into multiple "nested" promises with native JS.

I have a JSON with many sublevels as shown:

{
    "project": {
        "name": "TESTNAME",
        "label":"string11405",
        "description":"das",
    },
    "form": [{
        "label": "string",
        "name": "string",
        "fields": [{
            "label": "string",
            "name": "string",
            "field_type_id": "string",
            "meta": [{
                "meta_name": "string",
                "meta_value": "string"
            }]
       }]
}

So I have checked that I need to use Promise.all.

    return Promise.all(_.map(req.crfData ,(value,index,arr) => {
        var table = 'TABLE1';

        return conn.query(`INSERT INTO ${table} SET ?`,[value]);
    }))
    .then((result) => {
        var table = 'TABLE2';

        return Promise.all(_.map(req.fieldData ,(value,index,arr) => {
            value.crf_id = result.insertId;
            return conn.query(`INSERT INTO ${table} SET ?`,[value]);
        }));
    })
    .then((result) => {
        var table = 'TABLE3';

        return Promise.all(_.map(req.fieldData ,(value,index,arr) => {
            return conn.query(`INSERT INTO ${table} SET ?`,[value[0]],(err) => next(err));
        }));
    })
    .catch((err) => next(err));

The problem comes with the second query (TABLE2) where I can't retrieve the mysql new id from the previous promise because result contains a promise and not the appropiate data should be returned.

Thanks for the help.

Danibix
  • 235
  • 9
  • 18
Joss
  • 535
  • 1
  • 8
  • 28
  • I would expect the `result` to contain data from the first query. What is the `conole.log` of that result var? – steampowered Jun 29 '16 at 12:24
  • `result` contains an array with the results of the individual promises (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all#Using_Promise.all) – mhu Jun 29 '16 at 12:39

1 Answers1

1

Your first result argument will be an array of whatever conn.query() resolves with (that's what Promise.all() resolves with). So, result.insertId will be undefined since result is an array, not an object with named properties.

.insertId will be a property on each individual array element of result. If you want to read it from the last result returned by the previous query, then you would use something like this:

result[result.length - 1].insertId

Which is consistent with how .insertId is set for a single INSERT operation as shown here Return last inserted id with mySQL.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979