-1

I'm trying to upsert data to my database by doing an update query and if result.rowCount > 0 I console.log ('UPDATE Rows affected: ', result.rowCount); else inserting . This is the code I'm copying from which uses async and a callback:

(async () => {
   await client.query (updateQuery, (err, result)=>{
      try {
        if (err) throw err;
        if (result.rowCount > 0){
           console.log ('Rows affected: ', result.rowCount);
           return;
         } else {
           client.query(insertQuery, (error, res) =>{
           try {
             if (error) throw error;
             console.log ('Rows affected:', res.rowCount);
           }catch(er){
             console.log(er);
            }finally {
               //do something here
            }
          });
        }
       }catch (e){
         console.log(e);
        }
   });
  })().catch(e => console.log(e));

This code works if I'm trying to add it with the async and callback but how would I transform this to use .then?

DDavis25
  • 1,149
  • 1
  • 13
  • 25

1 Answers1

1

There are other responses in Stackoverflow that already explain what async/await are doing. Like this one

To your particular case in order to achieve what you are asking, assuming that your "client" returns a promise (judging by the fact that you can use await it looks like it does) remove the await and just call then for the successful path and catch for the error path and finally for the finally part, like this:

    client.query(updateQuery)
    .then((a) => {
      return a + 1;
    })
    .then((b) => {
       return b + 1; // b is whatever the previous `then` returned
    })
    .then((c) => {
      // something something
      return c;
    })
    .catch((err) => {
      // here be your error handling
    })
    .finally((x) => {
      // do a barrel roll
    })

  • But how would I get the result for the second query on this line `client.query(insertQuery, (error, res) =>{`. Do I need another `.then`? – DDavis25 Mar 06 '20 at 18:29
  • @DDavis25 whatever is returned in the previously returned promised is the argument that is passed to the next `then`. If you return `client.query`, the next `then` will have whatever `client.query` returns, if you just return a value, like in my example (post edit) then that value is what will be passed as an argument to the next then. – Jorge Armando Palm Mar 06 '20 at 23:32