0

I need to create an array with this structure:

[
 { 
   position: 2,
   family: 9404,
   part: [ 'article1', 'article2', 'article3' ]
 },
 {
   position: 3,
   family: 9405,
   part: [ 'article4', 'article5', 'article6' ] 
  }
]

So i have a form where i select the parts that i want and send the families to get url.In the getter function i do a for to get the articles of each family and i want to query a select of articles and a select of positions. After that i try to push each array to a main array but i can't, show me undefined. How can i do this kind of operations?

I'm new with node and express and this is the first time that i have to do that.

My code:

 getFamilies(req, res)
  {
    console.log(req.params.data);
    var parsedData = JSON.parse(req.params.data);
    var compounds = parsedData[0].compounds;
    var supplier = parsedData[0].supplier;
    var families = parsedData[0].families;
    console.log(parsedData[0].compounds.length);

    var position = [];

    var data = [];
    var parts = [];
    for (var i = 0; i < compounds.length; i++)
    {
      parts.push(request.query("SELECT st.ref, st.design FROM st WHERE familia ='"+families[i]+"'"));
      position.push(request.query("SELECT u_order FROM u_part WHERE u_familia='"+families[i]+"'"));
    }

    return Promise.all(parts, position, families).then(function(listOfResults)
    {
      //add parts, position and families to data[]
      var data = [];

      //console.log(data);
      console.log(listOfResults);
      console.log("done");
      //return listOfResults;
      res.render('view2', {teste: data});
    }).catch(function(err)
    {
        // ... query error checks
        console.log(err);
    });
  }

In promise just print the first parameter "parts" and if i put the [parts, position, families] give me promise pending. And how can i put the data in the structure that i show above.

parseData:

[
 {
   "compounds": ["8"],
   "supplier": ["sup"],
   "families": ["9305"]
  }
]

Please teach me how can i do this kind of operations.

Thank you

4
  • can you share what parsedData looks like? Commented Jan 11, 2017 at 11:01
  • Promise.all takes an array as argument so you have to concat your three arrays : Promise.all([...parts, ...position, ...families]) Commented Jan 11, 2017 at 11:04
  • 1
    parse data insert into resume @Guig Commented Jan 11, 2017 at 11:07
  • before the promise.all? @MatthieuLemoine Commented Jan 11, 2017 at 11:08

3 Answers 3

1
  • Not sure why you're passing families to Promise.all families seems to just be an array of data from taken from the query
  • Promise.all takes an array of promises in input, and you're passing an array of arrays of promises and of data...
  • you should never build SQL queries like this. This is a big flaw for SQL injection (but that's another question)

So do:

Promise.all([...parts, ...position]) or if you're not using ES6 syntax Promise.all(parts.concat(position))

and fix your SQL!

====

Final code could look like:

getFamilies = (req, res) => {
  var families = JSON.parse(req.params.data)[0].families;

  var positions = [];

  var data = [];
  var parts = [];
  families.forEach(family => {
    // see http://stackoverflow.com/a/7760578/2054629 for mysql_real_escape_string
    parts.push(request.query("SELECT st.ref, st.design FROM st WHERE familia ='"+mysql_real_escape_string(family)+"'"));
    positions.push(request.query("SELECT u_order FROM u_part WHERE u_familia='"+mysql_real_escape_string(family)+"'"));
  });

  return Promise.all([Promise.all(parts), Promise.all(positions)]).then(listOfResults => {
    var [partResult, positionResult] = listOfResults;

    var data = families.map((family, i) => {
      var pos = positionResult[i];
      var parts = partResult[i];
      return {family: family, position: pos, parts: parts};
    });
    res.render('view2', {teste: data});
  }).catch(err => {
      // ... query error checks
      console.log(err);
  });
};
Sign up to request clarification or add additional context in comments.

2 Comments

How can then we can extract part and position entites from next .then(result => )?
now returns a Promise Pending: [ { family: '9305', position: Promise { <pending> }, parts: Promise { <pending> } } ] @Guig
1

You incorrectly use Promise.all, it takes array of promises

return Promise.all([Promise.all(parts), Promise.all(position)]).then(function(listOfResults){
  var partResult = listOfResults[0];
  var positionResult = listOfResults[1];
  var data = [];
  for (var i=0; i<families.length; i++) {
     var family = families[i];
     var pos = positionResult[i];
     var parts = partResult; // logic to extract parts for current family
     data.push({family: family, position: pos, parts: parts})
  }
  console.log(data);
})

5 Comments

parts, positions, familiesare arrays you need to concat them first
Ok, thank you. I' using wrong the Promise. Now, don't show the position and parts... Print this: [ { family: '9301', position: [ [Object] ], parts: [ [Object] ] } ] @cevek
@user3242861 try to replace data.push with this data.push({family: family, position: pos[0].u_order, parts: parts.map(p => p.ref)})
works! :) but i need to pass all elements of parts. I'm trying this but not work: ... parts[0].map(p => p.ref, p.design)}); @cevek
@user3242861 then use just parts: parts
-1

Promise.all() takes an array of promises, it looks like you are passing multiple arrays.

1 Comment

Not array of function, array of promises

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.