thilina_hat
thilina_hat

Reputation: 23

Early returning inside an asynchronous function

Assume the scenario where you have to call an asynchronous function, but you are not really interested about success/failure situation of that function. In that case what are the pros and cons in following two patterns stated below with respect to call stack, callback queue and event loop

Pattern-1

async setSomething() {
    try {
        set(); // another async function
    } catch (err) {
        // log the error here
    }
    return true;
}

Pattern-2

async setSomething() {
    try {
        await set(); // another async function
    } catch (err) {
        // log the error here
    }
    return true;
}

Upvotes: 2

Views: 3824

Answers (2)

Dinesh Pandiyan
Dinesh Pandiyan

Reputation: 6289

This answer is a rather unconventional advice to the question than an actual answer to the examples posted by OP.

not really interested about success/failure situation of that function

If the above statement is the case, then it means, the return is not dependent on the result of the async invocation.

When you're not bothered about the return of the async invocation, it's better off to not use async/await or any type of promise at all. You could just invoke the function like any other function and process with the rest of the code.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370679

Pattern 1 does not catch any errors that may occur during asynchronous operations in the set function - any errors will result in an unhandled Promise rejection, which should be avoided. Pattern 1 will only catch errors that occur during set's synchronous operations (such as, when setting up a fetch request), which are not likely to occur in most situations.

Example:

// open your browser's console to see the uncaught rejection

const set = () => new Promise((_, reject) => setTimeout(reject, 500));
async function setSomething() {
    try {
        set(); // another async function
    } catch (err) {
        console.log('err');
    }
    return true;
}

setSomething();

So, pattern 2 is likely preferable. If you don't care about the result of the asynchronous call, then don't await or call .then when you call setSomething().

Or, for something this simple, you might consider using Promise methods only, no async function needed:

const setSomething = () => set()
  .catch((err) => {
    // log the error here
  });

Upvotes: 2

Related Questions