Angels
Angels

Reputation: 355

Best way to use asyn/await in the following code

I am kind of new in Javascript and I want to connect to DB and run a script. Then get the result of script and run functions in order. If there is any error with one of the functions, it should stop and doesnt run other functions.

I tried the following:

const {
  Client
} = require('pg')
const client = new Client({
  'connection info'
})

client.connect()
  .then(() => console.log('DB connected'))
  .catch(err => console.error('connection error', err.stack))

let dbResult

const data = async() => {
  try {
    dbResult = await client.query('SCRIPT') // array of json 
  } catch (error) {
    console.log(error);
  }
}

const func1 = async() => {
  try {
    // do something with dbResult
    console.log('func1 success msg')
  } catch (error) {
    console.log('error in func1')
  }
}

const func2 = async() => {
  try {
    // do something with dbResult
    console.log('func2 success msg')
  } catch (error) {
    console.log('error in func2')
  }
}

const func3 = async() => {
    dbResult.forEach(result => {
    // do something
})
  try {
    // do something with dbResult
    console.log('func3 success msg')
  } catch (error) {
    console.log('error in func3')
  }
}

data()
func1()
func2()
func3()

Upvotes: 0

Views: 64

Answers (2)

Jeremy Thille
Jeremy Thille

Reputation: 26400

All the functions you call are async, therefore return Promises and should be awaited. You can await all of them in a try/catch block, so if one fails, the others won't execute.

Don't use try/catch in each individual function, but rather here :

const data = async() => client.query('SCRIPT') // array of json 

const func1 = async() => console.log('func1 success msg')

const func2 = async() => console.log('func2 success msg')

const func3 = async() =>  dbResult.forEach(result => console.log(result))

(async () => {
    try{
        await client.connect();
        let dbResult = await data();
        dbResult = await func1(dbResult);
        await func2();
        await func3(dbResult);
    } catch(err) {
      console.log(err);
    }
})();

await Promise.all([data, func1, func2, func3]) would also fail if one of the Promises failed, but does not guarantee the execution order.

Upvotes: 2

Oleg Gulevskyy
Oleg Gulevskyy

Reputation: 102

Below is if you must use try catch inside each of your function body. If not, then I'd stick with the answer from Jeremy above.

What you can do is instead of console logging your errors that you receive in try..catch block, you can throw new error, which will stop the execution of your code and console log the actual error. (Well, not exactly console log, but rather console.error() it)

This will prevent the execution of other functions, unless you do something with your error (make some error handling where you can execute another code, depending on the error).

In general, the syntax for this as follows:

try {
  await someStuff();
} catch (err) {
  throw new Error(err)
}

Object err has some additional properties, such as name and message. Here is more about Error object.

Upvotes: 0

Related Questions