0

this mapping is supposed to append the result of the query inside to each object.

var newobj = obj.map(function (frequentPosition) {
    var query = `SQL query that uses attributes of obj`;
    sequelize.query(query).then(result => {
       obj.newArrayAttribute = result[0]; 
       return obj;
       });
    });

newobj returned is an array of undefined

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79

1 Answers1

0

Currently you do mutate theobjects asynchronously, however you do not wait for the async calls to finish thats why it looks as if the objects were never changed. Additionally you do not return anything from inside the .map, therefore newobj is an array of undefineds.

sequelize.query(query) already returns a promise, if you return that from the .map callback, you end up with an array of promises, which you can turn into a Promise that resolves to an array using Promise.all:

   const promise = Promise.all(obj.map(frequentPosition => {
    var query = `SQL query that uses attributes of obj`;
    return sequelize.query(query).then(result => {
      return { ...obj, newAttribute: result[0], };
    });
  });

Then you can use the promise as:

  promise.then(newobj => {
    // Do stuff with newobj
  });
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • this just returns Promise { } –  Jun 21 '19 at 09:13
  • @emma3 yup, thats exactly what you need. [Read on](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jonas Wilms Jun 21 '19 at 09:16
  • this appends all the new query results to the end of the array. I want queries to be executed per object and the result to be added to that object. –  Jun 21 '19 at 09:24
  • @emma3 well returning `obj` from the promise might not be what you want ... Yet you haven't used `frequentPosition`. – Jonas Wilms Jun 21 '19 at 09:26