0

I'm trying to create a new array object in my Promise function and I'm also trying to add user parameters from the getUser function.

I'm struggling to get the data into the array.

Could someone give me an example of how I could implement this?

Thanks.

      var results_array = [];
    return callHistory(76).then((result)=>{
        _.map(result, (item, index) => {
            var obj = JSON.parse(item.params);
            results_array[index] = {
                 id: item.id,
                 status: item.status,
                 timestamp: item.timestamp,
                 from_id:obj.from_id,
                 to_id: obj.to_id,
                 conference: obj.conference,
                 to:"",
                 from:getUser(10)

            };
        });


        res.json({
            status: 1,
            result: results_array
        })
        //return results_array;
    })

function getUser(id){

        return new Promise(function (resolve, reject) {
            connection.query(`SELECT * FROM members WHERE id = ${id} `, function (error, results, fields) {
                if (error) reject(error);
                return resolve(results);
            });
        });

    }
skirtle
  • 27,868
  • 4
  • 42
  • 57
Alex Malin
  • 63
  • 5

1 Answers1

2

At first lets beautify getUser a bit:

function getUser(id){
  return connection.query(`SELECT * FROM members WHERE id = ${id} `);
}

Async await can also be used in loops making your main loop more elegant too:

async function getHistory(index){
  const history = await callHistory(index), result = [];

  for(const call of history){
    const params = JSON.parse( call.params );
    params.to = "";
    params.from = await getUser( 10 /*params.from*/ );

    result.push( params );
  }
  return result;
}

Usable as:

getHistory(76)
  .then( result => res.json({status:1, result })
  .catch( error => res.json({status:500, error });
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • "*At first lets beautify getUser a bit*" - no, [you cannot replace the `new Promise` constructor with `async`/`await`](https://stackoverflow.com/q/45788934/1048572). `connection.query` takes a callback. – Bergi Oct 22 '17 at 10:21
  • @bergi maybe. E.g. the mongodb driver returns a promise if no callback was passed. That depends on the implementation ( and it looks like it *works* for the OP) – Jonas Wilms Oct 22 '17 at 12:26
  • Ah ok. Still, in that case you shouldn't use `async`/`await` either, just write ``function getUser(id){ return connection.query(`SELECT * FROM members WHERE id = ${id} `); }`` – Bergi Oct 22 '17 at 12:27