0

I'm having hard time with an array update in Node. Here is my problem : I make an API call to receive an array like this
[{id:1 name:x ...}{id:2 name:x ...} ]

I want to pass each line of this array to another query to update the name key (from number to string). Here is my code :

  axios(config)
   .then(function (response) {
     return response.data;
   })
   .then(function (response) {
     return Promise.all(response.myarray.map(entrie => {
       const sqlSelect = "SELECT * FROM table WHERE name = ?"
       db.query(sqlSelect, entrie.Id, (err, result) => {
         const new_name = result[0].name
         return { ...entrie, name: new_name }
       })
     }))
   })
   .then(function (response) {
     res.send(response)
   })
   .catch(function (error) {
     console.log(error);
   });
}

I Finally got an array of null values [null, null]

I don't know what's wrong because my SQL request works, the array update works when I use a define value for new_name instead of using SQL request. I feel that it has something to do with the asynchronous nature of Node but can't figure out what's wrong.

Thanks

Arthur Fortin
  • 103
  • 1
  • 10

1 Answers1

0

Promise.all expects an array of promises. Here you trying to return the result of the db query.

Try this.

.then(function (response) {
     return Promise.all(response.myarray.map(entrie => {
       const sqlSelect = "SELECT * FROM table WHERE name = ?"
       return db.query(sqlSelect, entrie.Id)
     }))
   }).then(db_result => { //do something })
  • Thanks for your answer. However it doesn't work. The last then doesn't return the result of the query result, but just the query with another parameters – Arthur Fortin Aug 10 '22 at 13:46