aesygod
aesygod

Reputation: 65

Is there any way to await and catch in javascript?

I am kind of new to async/await in javascript by have used suspend functionalities in Kotlin before. Is there any way to await and catch error if any in js. (without writing try catch). If not what is the right way to do this.

For example consider this snippet, async function a:

let a = async () => {
   // does io and returns result
}

Now, consider a function b which calls a. Can I write it in this clean way:

let a = async () => {
   const result_of_a = (await a()).catch(() => { // handle error }) 
   // work with `result_of_a`
}

Rather than

let a = async () => {
   var result_of_a = null
   try {
       result_of_a = await a()
   } catch (e) {

   }
   // work with `result_of_a`
}

Is there any other pretty way of writing the above sub-routine

Upvotes: 3

Views: 702

Answers (4)

Dumitru Birsan
Dumitru Birsan

Reputation: 837

for the sake of readability i would rather use a function which uses try/catch

async function errorControl(funcName) {
try{
   const data = await funcName()
    return [data, null]
  } catch (err) {
    return [null, err]
  }
}

and then you can use it like this

const b = async () => {
 const [result_of_a, err] = errorControl(a())
 if(err)
// do something 

}

it can also be use with promiseAll

const reqMultiple = async () => {
     const [result_of_a, result_of_b] = await Promise.all([
      errorControl(a()),
      errorControl(b())
     )]
  const [data_of_a,err_of_a] = result_of_a
 //...
    }

i prefer this way over the then/catch style because you don't have nested code which is a pain to read

Upvotes: 0

Shubham J.
Shubham J.

Reputation: 646

Can you try this way :

   let b = async () => {
       const result_of_a = await a().then(()=>{
         // handle success response here and return value
        },
        ()=>{
           // handle success response here and return value you want
          }
       )

   // You will get value return in `result_of_a`
}

Upvotes: 0

pz96
pz96

Reputation: 21

Use catch on a promise that is returned from your function. You mixed up two different approaches.

Upvotes: 0

Spankied
Spankied

Reputation: 1885

I don't believe you can. If you think .catch is cleaner perhaps you should just use promise syntax. Personally I use both, depending on the context. But I favor async due to promise hell

let asyncFn = async () => {
   const result = a().then(...).catch(...) 
}

Upvotes: 3

Related Questions