最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - should I always `await` on every promise? - Stack Overflow

programmeradmin7浏览0评论

I am having a hard time finding an answer about a question that puzzles me lately. should I always await on a promise ?

what do I mean by that?

Let's say I have a function the returns a promise, but I am not doing anything with the value that is returned from that promise. should I still await it ? or should I just leave it within a try catch

Should I await on function that returns Promise ?


const specialFunction = async () => {

  try {
    await handleEventsInsertion(body)
  } catch (error) {
    logger.error(error)
  }

}

the handleEventsInsertion method is the method that actually inserts the events to the database. but i am not doing anything with the promise that this method returns. so should i await anyway ? it results in an unhandled rejection if there is a reject

Is there a scenario where i should not await on a promise ?

I am having a hard time finding an answer about a question that puzzles me lately. should I always await on a promise ?

what do I mean by that?

Let's say I have a function the returns a promise, but I am not doing anything with the value that is returned from that promise. should I still await it ? or should I just leave it within a try catch

Should I await on function that returns Promise ?


const specialFunction = async () => {

  try {
    await handleEventsInsertion(body)
  } catch (error) {
    logger.error(error)
  }

}

the handleEventsInsertion method is the method that actually inserts the events to the database. but i am not doing anything with the promise that this method returns. so should i await anyway ? it results in an unhandled rejection if there is a reject

Is there a scenario where i should not await on a promise ?

Share Improve this question edited Nov 5, 2023 at 12:31 Eitank asked Oct 3, 2020 at 11:50 EitankEitank 69211 silver badges24 bronze badges 2
  • "it results in an unhandled rejection if there is a reject": yes it does. So what will you do? – trincot Commented Oct 3, 2020 at 11:53
  • it results in an unhandled rejection if there is a reject - this is a statement not a question. – Eitank Commented Oct 3, 2020 at 11:55
Add a ment  | 

1 Answer 1

Reset to default 8

No, you don't always need to await a promise. But, to ensure proper application flow, you should always be ready to handle any error that occurs.

If you do not await a promise, you should implement the catch callback. So either the code as you wrote it in your question, or something along the lines of:

const specialFunction = () => {
    handleEventInsertion(body)
        .catch(error => {
            logger.error(error);
        });
}

You can choose to not do that, but as you've already stated: if an error occurs and you do not try/await/catch the promise or .catch the error, it will be regarded as an unhandled rejection.

Edit:

As for your other question: is there a scenario where you should not await on a promise?

Yes. If you're responding to a user action that needs to report back immediately after triggering something that may take a while, you want that to be handled asynchronously and you don't want to wait for it to finish. But, in that case the asynchronous function you're calling should handle the error. As an example:

const onClick = () => {
    handleEventInsertion(body);  // asynchronous function
    alert("Thanks, we'll take it from here");
};

const handleEventInsertion = async (body) => {
    try {
        const result = await performLengthyAsyncOperation(body);
        alert(`${result} inserted successfully`);
    } catch (error) {
        logger.error(error);
    }

    // or using the callbacks instead of try/await/catch:
    performLengthyAsyncOperation(body)
        .then(result => {
            alert(`${result} inserted successfully`);
        }).catch(error => {
            logger.error(error);
        });
};

Edit 2:

If you, for some reason, really don't want to use await at all, there is an alternative solution: you can trap the unhandled rejection errors.

window.onunhandledrejection = (error) => {
    logger.error(error);
};

If you do that, you don't need to catch the error everywhere if the handling is always going to be same. In that case, you'd only await a promise if you need the result of the function or if a particular error requires special treatment.

发布评论

评论列表(0)

  1. 暂无评论