close

How to reject in async/await syntax?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to reject in async/await syntax? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to reject in async/await syntax ?

  1. How to reject in async/await syntax ?

    to reject in async/await syntax
    await foo().catch(error => console.log(error));
    This way you can avoid the try/catch syntax if you do not like it.

  2. How to reject in async/await syntax ?

    to reject in async/await syntax
    await foo().catch(error => console.log(error));
    This way you can avoid the try/catch syntax if you do not like it.

Method 1

It should probably also be mentioned that you can simply chain a catch() function after the call of your async operation because under the hood still a promise is returned.

await foo().catch(error => console.log(error));

This way you can avoid the try/catch syntax if you do not like it.

Method 2

You can create a wrapper function that takes in a promise and returns an array with data if no error and the error if there was an error.

function safePromise(promise) {
  return promise.then(data => [ data ]).catch(error => [ null, error ]);
}

Use it like this in ES7 and in an async function:

async function checkItem() {
  const [ item, error ] = await safePromise(getItem(id));
  if (error) { return null; } // handle error and return
  return item; // no error so safe to use item
}

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment